tool和model包阅读

master
gy 2 years ago
parent 6cce342b72
commit 71d2a819cb

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

@ -16,22 +16,6 @@
package net.micode.notes.model; 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 { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -43,17 +27,11 @@ public class WorkingNote {
private int mMode; private int mMode;
private long mAlertDate; private long mAlertDate;
private long mModifiedDate; private long mModifiedDate;
private int mBgColorId; private int mBgColorId;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private long mFolderId; private long mFolderId;
private Context mContext; private Context mContext;
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
@ -62,6 +40,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 声明 DATA_PROJECTION字符串数组
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -72,6 +51,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 声明 NOTE_PROJECTION字符串数组
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -82,33 +62,19 @@ public class WorkingNote {
}; };
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // New note construct
private WorkingNote(Context context, long folderId) //创建一个新的空白笔记。它初始化了一些基本属性 public WorkingNote(Context context, long folderId) {
{
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis();
mFolderId = folderId; mFolderId = folderId;
@ -119,9 +85,9 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// WorkingNote的构造函数
// Existing note construct // Existing note construct
private WorkingNote(Context context, long noteId, long folderId) //加载现有的笔记。它接受一个笔记ID和文件夹ID作为参数并加载对应的笔记数据。 private WorkingNote(Context context, long noteId, long folderId) {
{
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
mFolderId = folderId; mFolderId = folderId;
@ -130,12 +96,14 @@ public class WorkingNote {
loadNote(); loadNote();
} }
private void loadNote() //用于加载笔记的基本信息如背景颜色、小部件ID和类型、提醒日期等 // 加载Note
{ // 通过数据库调用query函数找到第一个条目
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
// 若存在,储存相应信息
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -146,6 +114,7 @@ public class WorkingNote {
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
} }
cursor.close(); cursor.close();
// 若不存在,报错
} else { } else {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
@ -153,15 +122,16 @@ public class WorkingNote {
loadNoteData(); loadNoteData();
} }
private void loadNoteData() //用于加载笔记的具体数据,如内容、模式等 // 加载NoteData
{ private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { // 查到信息不为空
if (cursor.moveToFirst()) { // 查看第一项是否存在
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
@ -173,7 +143,7 @@ public class WorkingNote {
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
} }
} while (cursor.moveToNext()); } while (cursor.moveToNext());//查阅所有项,直到为空
} }
cursor.close(); cursor.close();
} else { } else {
@ -182,10 +152,12 @@ public class WorkingNote {
} }
} }
// 创建空的Note
// 传参context文件夹idwidget背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, 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); WorkingNote note = new WorkingNote(context, folderId);
// 设定相关属性
note.setBgColorId(defaultBgColorId); note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId); note.setWidgetId(widgetId);
note.setWidgetType(widgetType); note.setWidgetType(widgetType);
@ -196,19 +168,17 @@ public class WorkingNote {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
public synchronized boolean saveNote() //保存便签 // 保存Note
{ public synchronized boolean saveNote() {
if (isWorthSaving())//首先检查便签是否值得保存。如果不值得保存则直接返回false if (isWorthSaving()) { //是否值得保存
{ if (!existInDatabase()) { // 是否存在数据库中
if (!existInDatabase()) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0)//调用Note.getNewNoteId方法获取一个新的笔记ID并将其赋值给mNoteId
{
Log.e(TAG, "Create new note fail with id:" + mNoteId); 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 * Update widget content if there exist any widget of this note
@ -217,20 +187,21 @@ public class WorkingNote {
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
}//如果笔记关联的小部件ID有效且小部件类型有效且存在笔记设置状态监听器则调用mNoteSettingStatusListener的onWidgetChanged方法来更新小部件的内容 }
return true; return true;
} else { } else {
return false; return false;
} }
} }
// 是否在数据库中存在
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
//用于检查笔记是否已存在于数据库中。它返回一个布尔值表示笔记是否存在于数据库中。如果笔记ID大于0则表示笔记已存在于数据库中
private boolean isWorthSaving()//用于判断笔记是否值得保存。它返回一个布尔值表示笔记是否值得保存。如果笔记已被标记为删除或者笔记不存在于数据库中且内容为空或者笔记存在于数据库中且没有本地修改则返回false否则返回true。 // 是否值得保存
{ private boolean isWorthSaving() {
// 被删除,或(不在数据库中 内容为空),或 本地已保存过
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -239,12 +210,15 @@ public class WorkingNote {
} }
} }
// 设置mNoteSettingStatusListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = 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) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
@ -254,18 +228,20 @@ public class WorkingNote {
} }
} }
public void markDeleted(boolean mark) //标记笔记是否已被删除。如果传入的标记值与当前标记值不同则更新笔记的删除标记并调用笔记设置状态监听器的onWidgetChanged方法 // 设定删除标记
{ public void markDeleted(boolean mark) {
// 设定标记
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
// 调用mNoteSettingStatusListener的 onWidgetChanged方法
} }
} }
public void setBgColorId(int id) //设置笔记的背景颜色。如果传入的颜色ID与当前颜色ID不同则更新笔记的颜色ID并调用笔记设置状态监听器的onBackgroundColorChanged方法 // 设定背景颜色
{ public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) { //设定条件 id != mBgColorId
mBgColorId = id; mBgColorId = id;
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
@ -274,9 +250,10 @@ public class WorkingNote {
} }
} }
public void setCheckListMode(int mode)//设置笔记的检查列表模式。如果传入的模式值与当前模式值不同则更新笔记的模式值并调用笔记设置状态监听器的onCheckListModeChanged方法 // 设定检查列表模式
{ // 参数mode
if (mMode != mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { //设定条件 mMode != mode
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -285,86 +262,108 @@ public class WorkingNote {
} }
} }
public void setWidgetType(int type) //用于设置笔记所属的小部件类型。如果传入的类型值与当前类型值不同,则更新笔记的类型值
{ // 设定WidgetType
if (type != mWidgetType) { // 参数type
public void setWidgetType(int type) {
if (type != mWidgetType) {//设定条件 type != mWidgetType
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
// 调用Note的setNoteValue方法更改WidgetType
} }
} }
public void setWidgetId(int id) //设置笔记所属的小部件ID。如果传入的ID值与当前ID值不同则更新笔记的ID值。 // 设定WidgetId
// 参数id
{ public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {//设定条件 id != mWidgetId
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
// 调用Note的setNoteValue方法更改WidgetId
} }
} }
public void setWorkingText(String text) //设置笔记的工作文本。如果传入的文本与当前文本不同,则更新笔记的文本值。 // 设定WorkingTex
{ // 参数更改的text
if (!TextUtils.equals(mContent, text)) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {//设定条件 mContent, text内容不同
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); 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.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
// 判断是否有时钟题型
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
//检查笔记是否设置了闹钟提醒。它返回一个布尔值表示笔记是否设置了闹钟提醒。如果笔记的提醒日期大于0则表示笔记设置了闹钟提醒
// 获取Content
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
//获取笔记的内容
// 获取AlertDate
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
//获取笔记的提醒日期
// 获取ModifiedDate
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
//获取笔记的修改日期
// 获取背景颜色来源id
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
//获取笔记的背景颜色资源ID
// 获取背景颜色id
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取标题背景颜色id
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
// 获取CheckListMode
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
// 获取便签id
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
//获取笔记的ID
// 获取文件夹id
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
//获取笔记所属的文件夹ID
// 获取WidgetId
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
//获取笔记所属的小部件ID
// 获取WidgetType
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
//用于获取笔记所属的小部件类型
// 创建接口 NoteSettingChangedListener,便签更新监视
// 为NoteEditActivity提供接口
// 提供函数有
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -14,101 +14,85 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.tool;// 声明包 package net.micode.notes.tool;
import android.content.Context;// 导入 Android 的 Context 类 public class BackupUtils {
import android.database.Cursor;// 导入 Android 的 Cursor 类 private static final String TAG = "BackupUtils";
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";// 定义日志标签
// Singleton stuff // Singleton stuff
private static BackupUtils sInstance; // 单例模式 private static BackupUtils sInstance; //类里面为什么可以定义自身类的对象?
public static synchronized BackupUtils getInstance(Context context) {// 获取单例实例的方法 public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {// 如果实例为空 //ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程例如线程A
sInstance = new BackupUtils(context);// 创建新的实例 //运行到这个方法时,都要检查有没有其它线程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 * Following states are signs to represents backup or restore
* status * status
*/ */
// Currently, the sdcard is not mounted // Currently, the sdcard is not mounted SD卡没有被装入手机
public static final int STATE_SD_CARD_UNMOUONTED = 0;// 表示当前 SD 卡未挂载 public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist // The backup file not exist 备份文件夹不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;// 备份文件不存在 public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs // The data is not well formated, may be changed by other programs 数据已被破坏,可能被修改
public static final int STATE_DATA_DESTROIED = 2;// 数据格式损毁,可能被其他程序修改 public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails // Some run-time exception which causes restore or backup fails 超时异常
public static final int STATE_SYSTEM_ERROR = 3;// 一些运行时异常导致恢复或备份失败 public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success // Backup or restore success 成功存储
public static final int STATE_SUCCESS = 4;// 备份或恢复成功 public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;// 文本导出实例 private TextExport mTextExport;
private BackupUtils(Context context) { private BackupUtils(Context context) { //初始化函数
mTextExport = new TextExport(context);// 初始化文本导出实例 mTextExport = new TextExport(context);
} }
private static boolean externalStorageAvailable() {// 检查外部存储是否可用 private static boolean externalStorageAvailable() { //外部存储功能是否可用
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
public int exportToText() {// 导出到文本方法 public int exportToText() {
return mTextExport.exportToText();// 调用文本导出实例的导出方法 return mTextExport.exportToText();
} }
public String getExportedTextFileName() {// 获取导出的文本文件名 public String getExportedTextFileName() {
return mTextExport.mFileName;// 返回导出的文本文件名 return mTextExport.mFileName;
} }
public String getExportedTextFileDir() {// 获取导出的文本文件目录 public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;// 返回导出的文本文件目录 return mTextExport.mFileDirectory;
} }
private static class TextExport {// 定义文本导出类 private static class TextExport {
private static final String[] NOTE_PROJECTION = {// 笔记投影数组 private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,// 笔记 ID NoteColumns.ID,
NoteColumns.MODIFIED_DATE, // 修改日期 NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,// 笔记片段 NoteColumns.SNIPPET,
NoteColumns.TYPE // 笔记类型 NoteColumns.TYPE
}; };
private static final int NOTE_COLUMN_ID = 0;// ID 列索引 private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;// 修改日期列索引 private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;// 碎片列索引 private static final int NOTE_COLUMN_SNIPPET = 2;
private static final String[] DATA_PROJECTION = {// 数据投影数组 private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,// 内容 DataColumns.CONTENT,
DataColumns.MIME_TYPE,// MIME 类型 DataColumns.MIME_TYPE,
DataColumns.DATA1,// 数据 1 DataColumns.DATA1,
DataColumns.DATA2,// 数据 2 DataColumns.DATA2,
DataColumns.DATA3,// 数据 3 DataColumns.DATA3,
DataColumns.DATA4,// 数据 4 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_MIME_TYPE = 1;
@ -117,45 +101,45 @@ public class BackupUtils { // 备份工具类定义开始
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private final String [] TEXT_FORMAT; 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_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2; private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;// 上下文和文件路径相关变量 private Context mContext;
private String mFileName; private String mFileName;
private String mFileDirectory; private String mFileDirectory;
public TextExport(Context context) {// 构造函数 public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context;
mFileName = ""; mFileName = ""; //为什么为空?
mFileDirectory = ""; mFileDirectory = "";
} }
private String getFormat(int id) { private String getFormat(int id) { //获取文本的组成部分
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
}// 获取指定格式的文本 }
/** /**
* Export the folder identified by folder id to text * Export the folder identified by folder id to text
*/ */
private void exportFolderToText(String folderId, PrintStream ps) {// 将文件夹导出为文本 private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
}, null); // 查询属于该文件夹的便签 }, null);
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { 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( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); 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); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps); //将文件导出到text
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
} }
notesCursor.close(); notesCursor.close();
@ -165,31 +149,31 @@ public class BackupUtils { // 备份工具类定义开始
/** /**
* Export note identified by id to a print stream * 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, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
}, null); }, null);
if (dataCursor != null) { if (dataCursor != null) { //利用光标来扫描内容区别为callnote和note两种靠ps.printline输出
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number// 打印电话号码 // Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) { if (!TextUtils.isEmpty(phoneNumber)) { //判断是否为空字符
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
} }
// Print call date// 打印通话日期 // Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), .format(mContext.getString(R.string.format_datetime_mdhm),
callDate))); callDate)));
// Print call attachment location// 打印通话附件位置 // Print call attachment location
if (!TextUtils.isEmpty(location)) { if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location)); location));
@ -205,7 +189,7 @@ public class BackupUtils { // 备份工具类定义开始
} }
dataCursor.close(); dataCursor.close();
} }
// print a line separator between note// 在便签之间加上一行分隔符 // print a line separator between note
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -218,18 +202,18 @@ public class BackupUtils { // 备份工具类定义开始
/** /**
* Note will be exported as text which is user readable * Note will be exported as text which is user readable
*/ */
public int exportToText() {// 检查外部存储是否可用 public int exportToText() { //总函数调用上面的exportFolder和exportNote
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
} }
// 获取导出文本的打印流
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream();
if (ps == null) { if (ps == null) {
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// First export folder and its notes// 首先导出文件夹及其笔记 // First export folder and its notes 导出文件夹,就是导出里面包含的便签
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -240,7 +224,7 @@ public class BackupUtils { // 备份工具类定义开始
if (folderCursor != null) { if (folderCursor != null) {
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) {
do { do {
// Print folder's 打印文件夹名称 // Print folder's name
String folderName = ""; String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { 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);
@ -257,7 +241,7 @@ public class BackupUtils { // 备份工具类定义开始
folderCursor.close(); folderCursor.close();
} }
// Export notes in root's folder// 导出根文件夹中的笔记 // Export notes in root's folder 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出)
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -297,7 +281,7 @@ public class BackupUtils { // 备份工具类定义开始
PrintStream ps = null; PrintStream ps = null;
try { try {
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos); ps = new PrintStream(fos); //将ps输出流输出到特定的文件目的就是导出到文件而不是直接输出
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -314,16 +298,16 @@ public class BackupUtils { // 备份工具类定义开始
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory()); sb.append(Environment.getExternalStorageDirectory()); //外部SD卡的存储路径
sb.append(context.getString(filePathResId)); sb.append(context.getString(filePathResId)); //文件的存储路径
File filedir = new File(sb.toString()); File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息
sb.append(context.getString( sb.append(context.getString(
fileNameFormatResId, fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd), DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis()))); System.currentTimeMillis())));
File file = new File(sb.toString()); File file = new File(sb.toString());
try { try { //如果这些文件不存在,则新建
if (!filedir.exists()) { if (!filedir.exists()) {
filedir.mkdir(); filedir.mkdir();
} }
@ -336,9 +320,8 @@ public class BackupUtils { // 备份工具类定义开始
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
// try catch 异常处理
return null; return null;
} }
} }

@ -16,97 +16,79 @@
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; public class DataUtils {
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 static final String TAG = "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) { if (ids == null) {
Log.d(TAG, "the ids is null");// 记录日志ids 为空 Log.d(TAG, "the ids is null");
return true; return true;
} }
if (ids.size() == 0) { 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; return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();// 创建操作列表 ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); //提供一个任务列表
for (long id : ids) {// 遍历需要删除的 ID并创建对应的删除操作 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"); Log.e(TAG, "Don't delete system folder root");
continue;// 如果是系统文件夹的 ID则跳过不执行删除操作 continue;
} } //如果发现是根文件夹,则不删除
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));// 创建删除操作 .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //用newDelete实现删除功能
operationList.add(builder.build());// 将操作添加到操作列表 operationList.add(builder.build()); //
} }
try { 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) { 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 false;
} }
return true; return true;
} catch (RemoteException e) { } 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) { } 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; return false;
} }
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {// 移动笔记到文件夹的方法 public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues();// 创建内容值对象 ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);// 设置父文件夹 ID values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);// 设置原始父文件夹 ID values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);// 设置本地修改标志 values.put(NoteColumns.LOCAL_MODIFIED, 1);
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);// 执行更新操作 resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); //对需要移动的便签进行数据更新然后用update实现
} }
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,// 批量移动笔记到文件夹的方法 public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null");// 记录日志ids 为空 Log.d(TAG, "the ids is null");
return true; return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();// 遍历需要移动的笔记 ID并创建对应的更新操作 ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));// 创建更新操作 .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //通过withAppendedId方法为该Uri加上ID
builder.withValue(NoteColumns.PARENT_ID, folderId);// 设置父文件夹 ID builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);// 设置本地修改标志 builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());// 将操作添加到操作列表 operationList.add(builder.build());
} }//将ids里包含的每一列的数据逐次加入到operationList中等待最后的批量处理
try { 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) { 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 false;
} }
return true; return true;
} catch (RemoteException e) { } 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) { } 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; return false;
} }
@ -114,38 +96,38 @@ public class DataUtils {// 定义日志标签
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} * 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, Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },// 查询结果为数量 new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null); null); //筛选条件源文件不为trash folder
int count = 0; int count = 0;
if(cursor != null) { if(cursor != null) {
if(cursor.moveToFirst()) { if(cursor.moveToFirst()) {
try { try {
count = cursor.getInt(0);// 获取数量 count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());// 记录日志,获取数量失败 Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
cursor.close();// 关闭游标 cursor.close();
} }
} }
} }
return count; return count;
} }
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {// 查询指定ID的笔记根据类型和父ID条件进行筛选 public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), //通过withAppendedId方法为该Uri加上ID
null, null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,// 传入需要查找的类型 NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)}, new String [] {String.valueOf(type)},
null); null); //查询条件type符合且不属于垃圾文件夹
boolean exist = false; boolean exist = false;
if (cursor != null) {// 判断是否存在记录 if (cursor != null) {
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -154,11 +136,11 @@ public class DataUtils {// 定义日志标签
} }
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { 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); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) {// 判断是否存在记录 if (cursor != null) {
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -167,12 +149,12 @@ public class DataUtils {// 定义日志标签
return exist; 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), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) {// 判断是否存在记录 if (cursor != null) {
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -181,14 +163,15 @@ public class DataUtils {// 定义日志标签
return exist; 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, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",// 传入需要查找的名称 " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false; boolean exist = false;
if(cursor != null) {// 判断是否存在记录 if(cursor != null) {
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -197,12 +180,12 @@ public class DataUtils {// 定义日志标签
return exist; 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, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",// 传入文件夹ID NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) }, new String[] { String.valueOf(folderId) },
null); null); //查询条件父ID是传入的folderId;
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null;
if (c != null) { if (c != null) {
@ -211,28 +194,28 @@ public class DataUtils {// 定义日志标签
do { do {
try { try {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0); widget.widgetId = c.getInt(0); //0对应的NoteColumns.WIDGET_ID
widget.widgetType = c.getInt(1); widget.widgetType = c.getInt(1); //1对应的NoteColumns.WIDGET_TYPE
set.add(widget); set.add(widget);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
} }
} while (c.moveToNext()); } while (c.moveToNext()); //查询下一条
} }
c.close(); c.close();
} }
return set; 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, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, 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 }, new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null); null);
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try {// 返回电话号码 try {
return cursor.getString(0); return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString()); Log.e(TAG, "Get call number fails " + e.toString());
@ -243,18 +226,19 @@ public class DataUtils {// 定义日志标签
return ""; 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, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" 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 }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null); null);
//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try {// 返回笔记ID try {
return cursor.getLong(0); return cursor.getLong(0); //0对应的CallNote.NOTE_ID
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString()); Log.e(TAG, "Get call note id fails " + e.toString());
} }
@ -264,12 +248,12 @@ public class DataUtils {// 定义日志标签
return 0; 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, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",// 传入笔记ID NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)}, new String [] { String.valueOf(noteId)},
null); null);//查询条件noteId
if (cursor != null) { if (cursor != null) {
String snippet = ""; String snippet = "";
@ -281,8 +265,7 @@ public class DataUtils {// 定义日志标签
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId); 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) { if (snippet != null) {
snippet = snippet.trim(); snippet = snippet.trim();
int index = snippet.indexOf('\n'); int index = snippet.indexOf('\n');
@ -292,4 +275,5 @@ public class DataUtils {// 定义日志标签
} }
return snippet; return snippet;
} }
} }

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

@ -16,11 +16,20 @@
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; /*使
import android.preference.PreferenceManager; * R.java
* R.id
import net.micode.notes.R; * R.drawable 使
import net.micode.notes.ui.NotesPreferenceActivity; * R.layout
* R.menu
* R.String
* R.style 使
* idgetXXX
*
*
* @BG_DEFAULT_COLOR
* BG_DEFAULT_FONT_SIZE
*/
public class ResourceParser { public class ResourceParser {
@ -54,7 +63,6 @@ public class ResourceParser {
R.drawable.edit_title_white, R.drawable.edit_title_white,
R.drawable.edit_title_green, R.drawable.edit_title_green,
R.drawable.edit_title_red R.drawable.edit_title_red
}; };
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
@ -65,7 +73,7 @@ public class ResourceParser {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
//直接获取默认的背景颜色。看不太懂这个PREFERENCE_SET_BG_COLOR_KEY是个final string,也就是说getBoolean肯定执行else为什么要这么写
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -163,6 +171,7 @@ public class ResourceParser {
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
//这里有一个容错的函数防止输入的id大于资源总量若如此则自动返回默认的设置结果
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.

Loading…
Cancel
Save