tool和model包阅读

master
gy 2 years ago
parent 6cce342b72
commit 71d2a819cb

@ -15,34 +15,27 @@
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
import android.content.ContentProviderOperation;//批量的更新、插入、删除数据。
import android.content.ContentProviderResult;//操作的结果
import android.content.ContentUris;//用于添加和获取Uri后面的ID
import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制
import android.content.Context;//需要用该类来弄清楚调用者的实例
import android.content.OperationApplicationException;//操作应用程序容错
import android.net.Uri;//表示待操作的数据
import android.os.RemoteException;//远程容错
import android.util.Log;//输出日志,比如说出错、警告等
public class Note {
private ContentValues mNoteDiffValues;//声明了一个私有变量mNoteDiffValues类型为ContentValues。这个变量用于存储笔记的差异值
private NoteData mNoteData;//声明了一个私有变量mNoteData类型为NoteData。这个变量用于存储笔记的数据
private static final String TAG = "Note";//声明了一个私有静态常量TAG类型为String值为"Note"。这个常量用于在日志中标识笔记类
// private ContentValues mNoteDiffValues;
ContentValues mNoteDiffValues;//
private NoteData mNoteData;
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) //这是一个公共静态同步方法用于获取一个新的笔记ID。该方法接收一个Context对象和一个文件夹ID作为参数并返回一个新的笔记ID
{
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
@ -50,69 +43,67 @@ public class Note {
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
//ContentResolver()主要是实现外部应用对ContentProvider中的数据
//进行添加、删除、修改和查询操作
long noteId = 0;
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
}//try-catch异常处理
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId;
}
public Note() //用于初始化mNoteDiffValues和mNoteData对象
{
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
public void setNoteValue(String key, String 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());
}
}//设置数据库表格的标签属性数据
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}//用于设置note的文本数据
}//设置数据库表格的标签文本内容的数据
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}//设置笔记的文本数据ID
}//设置文本数据ID
public long getTextDataId() {
return mNoteData.mTextDataId;
}//用于获取笔记的文本数据ID
}//得到文本数据的ID
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}//于设置笔记的通话数据ID
}//设置电话号码数据的ID
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}//用于设置笔记的通话数据
}//得到电话号码数据的ID
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}//同步笔记。它首先检查笔记是否有本地修改然后尝试更新数据库中的笔记信息和数据。如果更新失败则返回false。
public boolean syncNote(Context context, long noteId)//用于同步笔记的数据。它首先检查传入的笔记ID是否有效然后检查笔记是否有本地修改。如果没有本地修改则直接返回true。如果有本地修改它尝试更新数据库中的笔记信息。如果更新失败则记录错误日志并继续执行。然后清空笔记的差异值。接着检查笔记数据是否有本地修改如果有则尝试将数据推送到ContentResolver中。如果推送失败则返回false表示同步失败。最终返回true表示同步成功
{
}//判断是否是本地修改
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
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
@ -125,93 +116,82 @@ public class Note {
// Do not return, fall through
}
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}
return true;
}
private class NoteData //存储笔记的数据。它包含了文本数据ID、文本数据值、通话数据ID和通话数据值等属性。类中还包含了判断数据是否有本地修改的方法isLocalModified设置文本数据ID和通话数据ID的方法setTextDataId和setCallDataId以及设置文本数据和通话数据的方法setTextData和setCallData
{
}//判断数据是否同步
private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据
private long mTextDataId;
private ContentValues mTextDataValues;
private ContentValues mTextDataValues;//文本数据
private long mCallDataId;
private ContentValues mCallDataValues;
private ContentValues mCallDataValues;//电话号码数据
private static final String TAG = "NoteData";
public NoteData() //初始化笔记数据的值和ID
{
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
}
boolean isLocalModified()//用于检查笔记数据是否被本地修改过。如果文本数据或通话数据的值发生了改变则返回true
{
//下面是上述几个函数的具体实现
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
void setTextDataId(long id) //设置文本数据的ID
{
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
void setCallDataId(long id)//设置通话数据的ID
{
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}
void setCallData(String key, String value) //用于设置通话数据的键值对,并标记笔记数据已被本地修改
{
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
void setTextData(String key, String value)//用于设置文本数据的键值对,并标记笔记数据已被本地修改
{
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
Uri pushIntoContentResolver(Context context, long noteId)//用于将笔记数据推送到ContentResolver。它接受上下文和笔记ID作为参数并返回一个Uri对象。该方法首先检查笔记ID的有效性然后根据文本数据和通话数据的情况构建ContentProviderOperation列表并通过applyBatch方法将数据应用到ContentResolver。最终返回一个Uri对象表示数据的推送结果。
{
//下面函数的作用是将新的数据通过Uri的操作存储到数据库
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
if (noteId <= 0) //检查笔记ID是否小于等于0如果是则抛出IllegalArgumentException异常表示笔记ID不合法
{
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
}//判断数据是否合法
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) //检查文本数据的值是否存在
{
ContentProviderOperation.Builder builder = null;//数据库的操作列表
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) //检查文本数据的ID是否为0如果是则表示需要插入新的文本数据
{
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);//将文本数据的MIME类型添加到文本数据的值中
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);//将文本数据的值插入到ContentResolver中并返回插入数据的URI
mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));//从URI中获取插入数据的ID并设置为文本数据的ID
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
@ -219,15 +199,14 @@ public class Note {
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));//创建一个更新操作的ContentProviderOperation.Builder对象用于更新文本数据
builder.withValues(mTextDataValues);//将文本数据的值添加到更新操作中
operationList.add(builder.build());//将更新操作添加到操作列表中
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
mTextDataValues.clear();//清空文本数据的值,准备处理下一条数据
}
if(mCallDataValues.size() > 0) //检查通话数据的值是否存在,如果存在则进行类似的处理
{
mTextDataValues.clear();
}//把文本数据存入DataColumns
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
@ -247,14 +226,14 @@ public class Note {
operationList.add(builder.build());
}
mCallDataValues.clear();
}
}//把电话号码数据存入DataColumns
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);//根据操作的结果返回对应的URI如果操作失败则返回null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
@ -262,7 +241,7 @@ public class Note {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
}
}//存储过程中的异常处理
return null;
}
}

@ -15,23 +15,7 @@
*/
package net.micode.notes.model;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote {
// Note for the working note
private Note mNote;
@ -41,27 +25,22 @@ public class WorkingNote {
private String mContent;
// Note mode
private int mMode;
private long mAlertDate;
private long mModifiedDate;
private int mBgColorId;
private int mWidgetId;
private int mWidgetType;
private long mFolderId;
private Context mContext;
private static final String TAG = "WorkingNote";
private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener;
// 声明 DATA_PROJECTION字符串数组
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -71,7 +50,8 @@ public class WorkingNote {
DataColumns.DATA3,
DataColumns.DATA4,
};
// 声明 NOTE_PROJECTION字符串数组
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -80,35 +60,21 @@ public class WorkingNote {
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
};
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
private WorkingNote(Context context, long folderId) //创建一个新的空白笔记。它初始化了一些基本属性
{
public WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();
mFolderId = folderId;
@ -118,10 +84,10 @@ public class WorkingNote {
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// WorkingNote的构造函数
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) //加载现有的笔记。它接受一个笔记ID和文件夹ID作为参数并加载对应的笔记数据。
{
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
@ -129,13 +95,15 @@ public class WorkingNote {
mNote = new Note();
loadNote();
}
private void loadNote() //用于加载笔记的基本信息如背景颜色、小部件ID和类型、提醒日期等
{
// 加载Note
// 通过数据库调用query函数找到第一个条目
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()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -146,22 +114,24 @@ public class WorkingNote {
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() //用于加载笔记的具体数据,如内容、模式等
{
// 加载NoteData
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
// 查到信息不为空
if (cursor.moveToFirst()) { // 查看第一项是否存在
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
@ -173,7 +143,7 @@ public class WorkingNote {
} else {
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
} while (cursor.moveToNext());//查阅所有项,直到为空
}
cursor.close();
} else {
@ -181,35 +151,35 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
// 创建空的Note
// 传参context文件夹idwidget背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) //用于创建一个新的空白笔记。它接受上下文、文件夹ID、小部件ID、小部件类型和默认背景颜色ID作为参数并返回一个新的WorkingNote实例
{
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
// 设定相关属性
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
public synchronized boolean saveNote() //保存便签
{
if (isWorthSaving())//首先检查便签是否值得保存。如果不值得保存则直接返回false
{
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0)//调用Note.getNewNoteId方法获取一个新的笔记ID并将其赋值给mNoteId
{
// 保存Note
public synchronized boolean saveNote() {
if (isWorthSaving()) { //是否值得保存
if (!existInDatabase()) { // 是否存在数据库中
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;//如果获取失败返回的ID为0则记录错误日志并返回false
return false;
}
}
mNote.syncNote(mContext, mNoteId);//调用mNote对象的syncNote方法来同步笔记数据。这将尝试更新数据库中的笔记信息和数据
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
*/
@ -217,20 +187,21 @@ public class WorkingNote {
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}//如果笔记关联的小部件ID有效且小部件类型有效且存在笔记设置状态监听器则调用mNoteSettingStatusListener的onWidgetChanged方法来更新小部件的内容
}
return true;
} else {
return false;
}
}
// 是否在数据库中存在
public boolean existInDatabase() {
return mNoteId > 0;
}
//用于检查笔记是否已存在于数据库中。它返回一个布尔值表示笔记是否存在于数据库中。如果笔记ID大于0则表示笔记已存在于数据库中
private boolean isWorthSaving()//用于判断笔记是否值得保存。它返回一个布尔值表示笔记是否值得保存。如果笔记已被标记为删除或者笔记不存在于数据库中且内容为空或者笔记存在于数据库中且没有本地修改则返回false否则返回true。
{
// 是否值得保存
private boolean isWorthSaving() {
// 被删除,或(不在数据库中 内容为空),或 本地已保存过
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
@ -238,13 +209,16 @@ public class WorkingNote {
return true;
}
}
// 设置mNoteSettingStatusListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
public void setAlertDate(long date, boolean set) //用于设置提醒日期。如果传入的日期与当前日期不同则更新笔记的提醒日期并调用笔记设置状态监听器的onClockAlertChanged方法
{
// 设置AlertDate
// 若 mAlertDate与data不同则更改mAlertDate并设定NoteValue
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
@ -253,19 +227,21 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
public void markDeleted(boolean mark) //标记笔记是否已被删除。如果传入的标记值与当前标记值不同则更新笔记的删除标记并调用笔记设置状态监听器的onWidgetChanged方法
{
// 设定删除标记
public void markDeleted(boolean mark) {
// 设定标记
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
// 调用mNoteSettingStatusListener的 onWidgetChanged方法
}
}
public void setBgColorId(int id) //设置笔记的背景颜色。如果传入的颜色ID与当前颜色ID不同则更新笔记的颜色ID并调用笔记设置状态监听器的onBackgroundColorChanged方法
{
if (id != mBgColorId) {
// 设定背景颜色
public void setBgColorId(int id) {
if (id != mBgColorId) { //设定条件 id != mBgColorId
mBgColorId = id;
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
@ -273,10 +249,11 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}
public void setCheckListMode(int mode)//设置笔记的检查列表模式。如果传入的模式值与当前模式值不同则更新笔记的模式值并调用笔记设置状态监听器的onCheckListModeChanged方法
{
if (mMode != mode) {
// 设定检查列表模式
// 参数mode
public void setCheckListMode(int mode) {
if (mMode != mode) { //设定条件 mMode != mode
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
@ -284,103 +261,125 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}
}
public void setWidgetType(int type) //用于设置笔记所属的小部件类型。如果传入的类型值与当前类型值不同,则更新笔记的类型值
{
if (type != mWidgetType) {
// 设定WidgetType
// 参数type
public void setWidgetType(int type) {
if (type != mWidgetType) {//设定条件 type != mWidgetType
mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
// 调用Note的setNoteValue方法更改WidgetType
}
}
public void setWidgetId(int id) //设置笔记所属的小部件ID。如果传入的ID值与当前ID值不同则更新笔记的ID值。
{
if (id != mWidgetId) {
// 设定WidgetId
// 参数id
public void setWidgetId(int id) {
if (id != mWidgetId) {//设定条件 id != mWidgetId
mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
// 调用Note的setNoteValue方法更改WidgetId
}
}
public void setWorkingText(String text) //设置笔记的工作文本。如果传入的文本与当前文本不同,则更新笔记的文本值。
{
if (!TextUtils.equals(mContent, text)) {
// 设定WorkingTex
// 参数更改的text
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {//设定条件 mContent, text内容不同
mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent);
}//首先检查便签是否值得保存。如果不值得保存则直接返回false
// 调用Note的setTextData方法更改WorkingText
}
}
public void convertToCallNote(String phoneNumber, long callDate)//用于将笔记转换为通话记录笔记。它将笔记的类型设置为通话记录设置通话日期和电话号码并将笔记的父ID设置为通话记录文件夹的ID
{
// 转变mNote的CallData及CallNote信息
// 参数String phoneNumber, long 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));
}
// 判断是否有时钟题型
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
//检查笔记是否设置了闹钟提醒。它返回一个布尔值表示笔记是否设置了闹钟提醒。如果笔记的提醒日期大于0则表示笔记设置了闹钟提醒
// 获取Content
public String getContent() {
return mContent;
}
//获取笔记的内容
// 获取AlertDate
public long getAlertDate() {
return mAlertDate;
}
//获取笔记的提醒日期
// 获取ModifiedDate
public long getModifiedDate() {
return mModifiedDate;
}
//获取笔记的修改日期
// 获取背景颜色来源id
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
//获取笔记的背景颜色资源ID
// 获取背景颜色id
public int getBgColorId() {
return mBgColorId;
}
// 获取标题背景颜色id
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
// 获取CheckListMode
public int getCheckListMode() {
return mMode;
}
// 获取便签id
public long getNoteId() {
return mNoteId;
}
//获取笔记的ID
// 获取文件夹id
public long getFolderId() {
return mFolderId;
}
//获取笔记所属的文件夹ID
// 获取WidgetId
public int getWidgetId() {
return mWidgetId;
}
//获取笔记所属的小部件ID
// 获取WidgetType
public int getWidgetType() {
return mWidgetType;
}
//用于获取笔记所属的小部件类型
public interface NoteSettingChangedListener {
// 创建接口 NoteSettingChangedListener,便签更新监视
// 为NoteEditActivity提供接口
// 提供函数有
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*/
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

@ -14,182 +14,166 @@
* limitations under the License.
*/
package net.micode.notes.tool;// 声明包
import android.content.Context;// 导入 Android 的 Context 类
import android.database.Cursor;// 导入 Android 的 Cursor 类
import android.os.Environment;// 导入 Android 的 Environment 类
import android.text.TextUtils;// 导入 Android 的 TextUtils 类
import android.text.format.DateFormat;// 导入 Android 的 DateFormat 类
import android.util.Log;// 导入 Android 的 Log 类
import net.micode.notes.R;// 导入便签应用的资源类
import net.micode.notes.data.Notes;// 导入便签应用的 Notes 类
import net.micode.notes.data.Notes.DataColumns; // 导入便签应用的数据列类
import net.micode.notes.data.Notes.DataConstants;// 导入便签应用的数据常量类
import net.micode.notes.data.Notes.NoteColumns;// 导入便签应用的便签列类
import java.io.File;// 导入文件类
import java.io.FileNotFoundException;// 导入文件未找到异常类
import java.io.FileOutputStream;// 导入文件输出流类
import java.io.IOException;// 导入 IO 异常类
import java.io.PrintStream;// 导入打印流类
public class BackupUtils { // 备份工具类定义开始
private static final String TAG = "BackupUtils";// 定义日志标签
package net.micode.notes.tool;
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);// 创建新的实例
private static BackupUtils sInstance; //类里面为什么可以定义自身类的对象?
public static synchronized BackupUtils getInstance(Context context) {
//ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程例如线程A
//运行到这个方法时,都要检查有没有其它线程B或者C、 D等正在用这个方法(或者该类的其他同步方法)有的话要等正在使用synchronized方法的线程B或者C 、D运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。
//它包括两种用法synchronized 方法和 synchronized 块。
if (sInstance == null) {
//如果当前备份不存在,则新声明一个
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;// 表示当前 SD 卡未挂载
// 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);// 初始化文本导出实例
// Currently, the sdcard is not mounted SD卡没有被装入手机
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() {// 检查外部存储是否可用
private static boolean externalStorageAvailable() { //外部存储功能是否可用
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
public int exportToText() {// 导出到文本方法
return mTextExport.exportToText();// 调用文本导出实例的导出方法
public int exportToText() {
return mTextExport.exportToText();
}
public String getExportedTextFileName() {// 获取导出的文本文件名
return mTextExport.mFileName;// 返回导出的文本文件名
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
public String getExportedTextFileDir() {// 获取导出的文本文件目录
return mTextExport.mFileDirectory;// 返回导出的文本文件目录
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
private static class TextExport {// 定义文本导出类
private static final String[] NOTE_PROJECTION = {// 笔记投影数组
NoteColumns.ID,// 笔记 ID
NoteColumns.MODIFIED_DATE, // 修改日期
NoteColumns.SNIPPET,// 笔记片段
NoteColumns.TYPE // 笔记类型
private static class TextExport {
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
};
private static final int NOTE_COLUMN_ID = 0;// ID 列索引
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,// MIME 类型
DataColumns.DATA1,// 数据 1
DataColumns.DATA2,// 数据 2
DataColumns.DATA3,// 数据 3
DataColumns.DATA4,// 数据 4
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,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
private static final int DATA_COLUMN_CONTENT = 0;// 定义数据列的常量
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_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;// 上下文和文件路径相关变量
private Context mContext;
private String mFileName;
private String mFileDirectory;
public TextExport(Context context) {// 构造函数
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileName = ""; //为什么为空?
mFileDirectory = "";
}
private String getFormat(int id) {
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
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null); // 查询属于该文件夹的便签
if (notesCursor != null) {
folderId
}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date// 打印便签的最后修改日期
// Print note's last modified date ps里面保存有这份note的日期
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// 查询属于该便签的数据
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
exportNoteToText(noteId, ps); //将文件导出到text
} while (notesCursor.moveToNext());
}
notesCursor.close();
}
}
/**
* Export note identified by id to a print stream
*/
private void exportNoteToText(String noteId, PrintStream ps) {// 将便签导出为文本
private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
noteId
}, null);
if (dataCursor != null) {
if (dataCursor != null) { //利用光标来扫描内容区别为callnote和note两种靠ps.printline输出
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number// 打印电话号码
// 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);
if (!TextUtils.isEmpty(phoneNumber)) {
if (!TextUtils.isEmpty(phoneNumber)) { //判断是否为空字符
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date// 打印通话日期
// 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// 打印通话附件位置
// Print call attachment location
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
@ -205,7 +189,7 @@ public class BackupUtils { // 备份工具类定义开始
}
dataCursor.close();
}
// print a line separator between note// 在便签之间加上一行分隔符
// print a line separator between note
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -214,33 +198,33 @@ public class BackupUtils { // 备份工具类定义开始
Log.e(TAG, e.toString());
}
}
/**
* Note will be exported as text which is user readable
*/
public int exportToText() {// 检查外部存储是否可用
public int exportToText() { //总函数调用上面的exportFolder和exportNote
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// 首先导出文件夹及其笔记
// 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 打印文件夹名称
// 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);
@ -256,14 +240,14 @@ public class BackupUtils { // 备份工具类定义开始
}
folderCursor.close();
}
// Export notes in root's folder// 导出根文件夹中的笔记
// 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 {
@ -278,14 +262,14 @@ public class BackupUtils { // 备份工具类定义开始
noteCursor.close();
}
ps.close();
return STATE_SUCCESS;
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
@ -297,7 +281,7 @@ public class BackupUtils { // 备份工具类定义开始
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
ps = new PrintStream(fos); //将ps输出流输出到特定的文件目的就是导出到文件而不是直接输出
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
@ -308,22 +292,22 @@ public class BackupUtils { // 备份工具类定义开始
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(Environment.getExternalStorageDirectory()); //外部SD卡的存储路径
sb.append(context.getString(filePathResId)); //文件的存储路径
File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
File file = new File(sb.toString());
try {
try { //如果这些文件不存在,则新建
if (!filedir.exists()) {
filedir.mkdir();
}
@ -336,9 +320,8 @@ public class BackupUtils { // 备份工具类定义开始
} catch (IOException e) {
e.printStackTrace();
}
// try catch 异常处理
return null;
}
}

@ -15,150 +15,132 @@
*/
package net.micode.notes.tool;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
public class DataUtils {// 定义日志标签
public class DataUtils {
public static final String TAG = "DataUtils";
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {// 批量删除笔记的方法
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { //直接删除多个笔记
if (ids == null) {
Log.d(TAG, "the ids is null");// 记录日志ids 为空
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");// 记录日志ids 集合中没有 ID
Log.d(TAG, "no id is in the hashset");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();// 创建操作列表
for (long id : ids) {// 遍历需要删除的 ID并创建对应的删除操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); //提供一个任务列表
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;// 如果是系统文件夹的 ID则跳过不执行删除操作
}
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)); //用newDelete实现删除功能
operationList.add(builder.build()); //
}
try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);// 应用批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//主机名或叫Authority用于唯一标识这个ContentProvider外部调用者可以根据这个标识来找到它。
//数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());// 记录日志,删除失败
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()));// 记录远程异常日志
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()));// 记录操作异常日志
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 values = new ContentValues();// 创建内容值对象
values.put(NoteColumns.PARENT_ID, desFolderId);// 设置父文件夹 ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);// 设置原始父文件夹 ID
values.put(NoteColumns.LOCAL_MODIFIED, 1);// 设置本地修改标志
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);// 执行更新操作
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); //对需要移动的便签进行数据更新然后用update实现
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,// 批量移动笔记到文件夹的方法
long folderId) {
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
if (ids == null) {
Log.d(TAG, "the ids is null");// 记录日志ids 为空
Log.d(TAG, "the ids is null");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();// 遍历需要移动的笔记 ID并创建对应的更新操作
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);// 设置父文件夹 ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);// 设置本地修改标志
operationList.add(builder.build());// 将操作添加到操作列表
}
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //通过withAppendedId方法为该Uri加上ID
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
}//将ids里包含的每一列的数据逐次加入到operationList中等待最后的批量处理
try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);// 应用批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); //applyBatch一次性处理一个操作列表
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());// 记录日志,删除失败
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()));// 记录远程异常日志
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()));// 记录操作异常日志
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) {// 获取用户文件夹数量(排除系统文件夹)
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },// 查询结果为数量
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
null); //筛选条件源文件不为trash folder
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);// 获取数量
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());// 记录日志,获取数量失败
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();// 关闭游标
cursor.close();
}
}
}
return count;
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {// 查询指定ID的笔记根据类型和父ID条件进行筛选
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), //通过withAppendedId方法为该Uri加上ID
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,// 传入需要查找的类型
new String [] {String.valueOf(type)},
null);
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null); //查询条件type符合且不属于垃圾文件夹
boolean exist = false;
if (cursor != null) {// 判断是否存在记录
if (cursor.getCount() > 0) {
if (cursor != null) {
if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空
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),// 查询指定ID的笔记
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {// 判断是否存在记录
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
@ -166,13 +148,13 @@ public class DataUtils {// 定义日志标签
}
return exist;
}
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {// 查询指定ID的数据
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 != null) {
if (cursor.getCount() > 0) {
exist = true;
}
@ -180,15 +162,16 @@ public class DataUtils {// 定义日志标签
}
return exist;
}
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {// 查询非回收站中特定名称的文件夹笔记
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 + "=?",// 传入需要查找的名称
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false;
if(cursor != null) {// 判断是否存在记录
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
}
@ -196,14 +179,14 @@ public class DataUtils {// 定义日志标签
}
return exist;
}
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {// 获取文件夹笔记的小部件数据
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 + "=?",// 传入文件夹ID
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
null); //查询条件父ID是传入的folderId;
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
@ -211,28 +194,28 @@ public class DataUtils {// 定义日志标签
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
widget.widgetId = c.getInt(0); //0对应的NoteColumns.WIDGET_ID
widget.widgetType = c.getInt(1); //1对应的NoteColumns.WIDGET_TYPE
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
} while (c.moveToNext()); //查询下一条
}
c.close();
}
return set;
}
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {// 通过笔记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 + "=?",// 传入笔记ID和MIME类型
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
if (cursor != null && cursor.moveToFirst()) {
try {// 返回电话号码
try {
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
@ -242,19 +225,20 @@ public class DataUtils {// 定义日志标签
}
return "";
}
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {// 通过电话号码和通话日期获取笔记ID
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 + ",?)",// 传入通话日期、MIME类型和电话号码
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) {
if (cursor.moveToFirst()) {
try {// 返回笔记ID
return cursor.getLong(0);
try {
return cursor.getLong(0); //0对应的CallNote.NOTE_ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
@ -263,14 +247,14 @@ public class DataUtils {// 定义日志标签
}
return 0;
}
public static String getSnippetById(ContentResolver resolver, long noteId) {// 通过笔记ID获取摘要内容
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",// 传入笔记ID
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
null);//查询条件noteId
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
@ -281,8 +265,7 @@ public class DataUtils {// 定义日志标签
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
public static String getFormattedSnippet(String snippet) {// 对摘要内容进行格式化处理
public static String getFormattedSnippet(String snippet) { //对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
@ -292,4 +275,5 @@ public class DataUtils {// 定义日志标签
}
return snippet;
}
}
}

@ -14,100 +14,102 @@
* limitations under the License.
*/
//简介定义了很多的静态字符串目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范
package net.micode.notes.tool;
public class GTaskStringUtils {
//这个类就是定义了一堆static string实际就是为jsonObject提供Key把这些定义全部写到一个类里方便查看管理是一个非常好的编程习惯
public class GTaskStringUtils {
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";
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";
}
}

@ -15,58 +15,66 @@
*/
package net.micode.notes.tool;
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/*使
* R.java
* R.id
* R.drawable 使
* R.layout
* R.menu
* R.String
* R.style 使
* idgetXXX
*
*
* @BG_DEFAULT_COLOR
* BG_DEFAULT_FONT_SIZE
*/
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,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
public static int getDefaultBgId(Context context) {
//直接获取默认的背景颜色。看不太懂这个PREFERENCE_SET_BG_COLOR_KEY是个final string,也就是说getBoolean肯定执行else为什么要这么写
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
@ -74,95 +82,96 @@ public class ResourceParser {
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,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[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 {
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
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,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
//这里有一个容错的函数防止输入的id大于资源总量若如此则自动返回默认的设置结果
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
@ -174,9 +183,9 @@ public class ResourceParser {
}
return TEXTAPPEARANCE_RESOURCES[id];
}
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}
Loading…
Cancel
Save