Compare commits

...

No commits in common. 'develop' and 'master' have entirely different histories.

@ -0,0 +1,2 @@
# Java

@ -60,7 +60,7 @@ public class Contact {
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
} finally { } finally {
cursor.close(); cursor.close();

@ -66,105 +66,105 @@ public class Notes {
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String ID = "_id"; public static final String ID = "_id";
/** /**
* The parent's id for note or folder * The parent's id for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date * Latest modified date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Alert date * Alert date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";
/** /**
* Folder's name or text content of note * Folder's name or text content of note
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
/** /**
* Note's widget id * Note's widget id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
/** /**
* Note's widget type * Note's widget type
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
/** /**
* Note's background color's id * Note's background color's id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";
/** /**
* For text note, it doesn't has attachment, for multi-media * For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment * note, it has at least one attachment
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment";
/** /**
* Folder's count of notes * Folder's count of notes
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";
/** /**
* The file type: folder or note * The file type: folder or note
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
String TYPE = "type"; public static final String TYPE = "type";
/** /**
* The last sync id * The last sync id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
/** /**
* Sign to indicate local modified or not * Sign to indicate local modified or not
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
/** /**
* Original parent id before moving into temporary folder * Original parent id before moving into temporary folder
* <P> Type : INTEGER </P> * <P> Type : INTEGER </P>
*/ */
String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/** /**
* The gtask id * The gtask id
* <P> Type : TEXT </P> * <P> Type : TEXT </P>
*/ */
String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
/** /**
* The version code * The version code
* <P> Type : INTEGER (long) </P> * <P> Type : INTEGER (long) </P>
*/ */
String VERSION = "version"; public static final String VERSION = "version";
} }
public interface DataColumns { public interface DataColumns {
@ -172,73 +172,73 @@ public class Notes {
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String ID = "_id"; public static final String ID = "_id";
/** /**
* The MIME type of the item represented by this row. * The MIME type of the item represented by this row.
* <P> Type: Text </P> * <P> Type: Text </P>
*/ */
String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";
/** /**
* The reference id to note that this data belongs to * The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date * Latest modified date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Data's content * Data's content
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
String CONTENT = "content"; public static final String CONTENT = "content";
/** /**
* Generic data column, the meaning is specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
String DATA1 = "data1"; public static final String DATA1 = "data1";
/** /**
* Generic data column, the meaning is specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
String DATA2 = "data2"; public static final String DATA2 = "data2";
/** /**
* Generic data column, the meaning is specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
String DATA3 = "data3"; public static final String DATA3 = "data3";
/** /**
* Generic data column, the meaning is specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
String DATA4 = "data4"; public static final String DATA4 = "data4";
/** /**
* Generic data column, the meaning is specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {

@ -33,9 +33,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
public interface TABLE { public interface TABLE {
String NOTE = "note"; public static final String NOTE = "note";
String DATA = "data"; public static final String DATA = "data";
} }
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";

@ -73,7 +73,7 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
private static final String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
@ -135,7 +135,7 @@ public class NotesProvider extends ContentProvider {
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString });
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex); Log.e(TAG, "got exception: " + ex.toString());
} }
break; break;
default: default:
@ -159,7 +159,7 @@ public class NotesProvider extends ContentProvider {
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values); Log.d(TAG, "Wrong data format without note id:" + values.toString());
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
@ -198,7 +198,7 @@ public class NotesProvider extends ContentProvider {
* ID that smaller than 0 is system folder which is not allowed to * ID that smaller than 0 is system folder which is not allowed to
* trash * trash
*/ */
long noteId = Long.parseLong(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
break; break;
} }
@ -240,7 +240,7 @@ public class NotesProvider extends ContentProvider {
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.parseLong(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
@ -283,7 +283,7 @@ public class NotesProvider extends ContentProvider {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
if (id > 0) { if (id > 0) {
sql.append(NoteColumns.ID + "=" + id); sql.append(NoteColumns.ID + "=" + String.valueOf(id));
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection;

@ -55,7 +55,7 @@ public class SqlData {
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private final ContentResolver mContentResolver; private ContentResolver mContentResolver;
private boolean mIsCreate; private boolean mIsCreate;
@ -69,7 +69,7 @@ public class SqlData {
private String mDataContentData3; private String mDataContentData3;
private final ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -154,9 +154,9 @@ public class SqlData {
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
mDataId = Long.parseLong(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
} else { } else {

@ -86,9 +86,9 @@ public class SqlNote {
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
private final Context mContext; private Context mContext;
private final ContentResolver mContentResolver; private ContentResolver mContentResolver;
private boolean mIsCreate; private boolean mIsCreate;
@ -118,9 +118,9 @@ public class SqlNote {
private long mVersion; private long mVersion;
private final ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
private final ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
@ -226,7 +226,7 @@ public class SqlNote {
} }
} }
public void setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
@ -354,7 +354,9 @@ public class SqlNote {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return false;
} }
return true;
} }
public JSONObject getContent() { public JSONObject getContent() {
@ -446,9 +448,9 @@ public class SqlNote {
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try { try {
mId = Long.parseLong(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
if (mId == 0) { if (mId == 0) {

@ -35,7 +35,7 @@ public class TaskList extends Node {
private int mIndex; private int mIndex;
private final ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
public TaskList() { public TaskList() {
super(); super();
@ -220,7 +220,7 @@ public class TaskList extends Node {
return mChildren.size(); return mChildren.size();
} }
public void addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
@ -231,6 +231,7 @@ public class TaskList extends Node {
task.setParent(this); task.setParent(this);
} }
} }
return ret;
} }
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {

@ -31,19 +31,19 @@ import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static final int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
private final Context mContext; private Context mContext;
private final NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
private final GTaskManager mTaskManager; private GTaskManager mTaskManager;
private final OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
@ -119,7 +119,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} }
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(() -> mOnCompleteListener.onComplete()).start(); new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
} }
} }
} }

@ -143,8 +143,8 @@ public class GTaskClient {
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url + "ig"; mGetUrl = url.toString() + "ig";
mPostUrl = url + "r/ig"; mPostUrl = url.toString() + "r/ig";
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true; mLoggedin = true;
@ -208,7 +208,7 @@ public class GTaskClient {
} }
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // maybe the auth token is out of date, now let's invalidate the
// token and try again // token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
@ -217,7 +217,7 @@ public class GTaskClient {
return false; return false;
} }
if (loginGtask(authToken)) { if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed"); Log.e(TAG, "login gtask failed");
return false; return false;
} }
@ -270,14 +270,14 @@ public class GTaskClient {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return true; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions // simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return true; return false;
} }
return false; return true;
} }
private int getActionId() { private int getActionId() {

@ -46,7 +46,6 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Objects;
public class GTaskManager { public class GTaskManager {
@ -74,19 +73,19 @@ public class GTaskManager {
private boolean mCancelled; private boolean mCancelled;
private final HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
private final HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
private final HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList; private TaskList mMetaList;
private final HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
private final HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
private final HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
@ -328,7 +327,9 @@ public class GTaskManager {
} }
// go through remaining items // go through remaining items
for (Map.Entry<String, Node> entry : mGTaskHashMap.entrySet()) { Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue(); node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
} }
@ -377,7 +378,7 @@ public class GTaskManager {
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else { } else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, null, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} else { } else {
Log.w(TAG, "failed to query root folder"); Log.w(TAG, "failed to query root folder");
@ -410,7 +411,7 @@ public class GTaskManager {
+ GTaskStringUtils.FOLDER_CALL_NOTE)) + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else { } else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, null, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} }
} else { } else {
@ -460,7 +461,9 @@ public class GTaskManager {
} }
// for remote add folders // for remote add folders
for (Map.Entry<String, TaskList> entry : mGTaskListHashMap.entrySet()) { Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
gid = entry.getKey(); gid = entry.getKey();
node = entry.getValue(); node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) { if (mGTaskHashMap.containsKey(gid)) {
@ -504,6 +507,8 @@ public class GTaskManager {
updateLocalNode(node, c); updateLocalNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_REMOTE: case Node.SYNC_ACTION_UPDATE_REMOTE:
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea // merging both modifications maybe a good idea
// right now just use local update simply // right now just use local update simply
@ -576,7 +581,7 @@ public class GTaskManager {
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node"); throw new ActionFailureException("cannot add local node");
} }
sqlNote.setParentId(parentId); sqlNote.setParentId(parentId.longValue());
} }
// create the local node // create the local node
@ -607,7 +612,7 @@ public class GTaskManager {
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node"); throw new ActionFailureException("cannot update local node");
} }
sqlNote.setParentId(parentId); sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // update meta info
@ -632,7 +637,7 @@ public class GTaskManager {
Log.e(TAG, "cannot find task's parent tasklist"); Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task"); throw new ActionFailureException("cannot add remote task");
} }
Objects.requireNonNull(mGTaskListHashMap.get(parentGid)).addChildTask(task); mGTaskListHashMap.get(parentGid).addChildTask(task);
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
@ -651,7 +656,9 @@ public class GTaskManager {
else else
folderName += sqlNote.getSnippet(); folderName += sqlNote.getSnippet();
for (Map.Entry<String, TaskList> entry : mGTaskListHashMap.entrySet()) { Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey(); String gid = entry.getKey();
TaskList list = entry.getValue(); TaskList list = entry.getValue();
@ -713,9 +720,7 @@ public class GTaskManager {
if (preParentList != curParentList) { if (preParentList != curParentList) {
preParentList.removeChildTask(task); preParentList.removeChildTask(task);
if (curParentList != null) { curParentList.addChildTask(task);
curParentList.addChildTask(task);
}
GTaskClient.getInstance().moveTask(task, preParentList, curParentList); GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
} }
} }

@ -44,10 +44,12 @@ public class GTaskSyncService extends Service {
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, () -> { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
mSyncTask = null; public void onComplete() {
sendBroadcast(""); mSyncTask = null;
stopSelf(); sendBroadcast("");
stopSelf();
}
}); });
sendBroadcast(""); sendBroadcast("");
mSyncTask.execute(); mSyncTask.execute();

@ -15,15 +15,15 @@
*/ */
package net.micode.notes.model; package net.micode.notes.model;
import android.content.ContentProviderOperation; //批量的更新、插入、删除 import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; //操作的结果 import android.content.ContentProviderResult;
import android.content.ContentUris; //用于添加和获取uri后面的ID import android.content.ContentUris;
import android.content.ContentValues; //一种用于存储基本数据类型数据的存储机制 import android.content.ContentValues;
import android.content.Context; //需要用该类来弄清楚调用者的实例 import android.content.Context;
import android.content.OperationApplicationException;//操作应用程序容错 import android.content.OperationApplicationException;
import android.net.Uri; //表示待操作的数据 import android.net.Uri;
import android.os.RemoteException; //远程容错 import android.os.RemoteException;
import android.util.Log; //输出日志,比如出错警告等 import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
@ -35,8 +35,8 @@ import java.util.ArrayList;
public class Note { public class Note {
private final ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
private final NoteData mNoteData; private NoteData mNoteData;
private static final String TAG = "Note"; 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
@ -49,17 +49,16 @@ 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.parseLong(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); 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);
} }
@ -69,45 +68,45 @@ public class Note {
public Note() { 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);
} //设置数据库表格的标签文本内容的数据 }
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
}//设置文本数据的ID }
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
}//得到文本数据的ID }
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(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();
}//判断是否本地修改 }
public void syncNote(Context context, long noteId) { 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);
} }
if (isLocalModified()) { if (!isLocalModified()) {
return; return true;
} }
/** /**
@ -125,18 +124,20 @@ public class Note {
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
} }
}//判断数据是否同步 return true;
}
private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据 private class NoteData {
private long mTextDataId; private long mTextDataId;
private final ContentValues mTextDataValues;//文本数据 private ContentValues mTextDataValues;
private long mCallDataId; private long mCallDataId;
private final ContentValues mCallDataValues;//电话号码数据 private ContentValues mCallDataValues;
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
@ -146,7 +147,7 @@ public class Note {
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
//下面是上述几个函数的具体实现
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
@ -176,17 +177,17 @@ public class Note {
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//
Uri pushIntoContentResolver(Context context, long noteId) {//将新的数据通过uri的操作存储到数据库 Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
if (noteId <= 0) { 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);
@ -195,7 +196,7 @@ public class Note {
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
try { try {
setTextDataId(Long.parseLong(uri.getPathSegments().get(1))); 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();
@ -208,7 +209,7 @@ public class Note {
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);
@ -217,7 +218,7 @@ public class Note {
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues); mCallDataValues);
try { try {
setCallDataId(Long.parseLong(uri.getPathSegments().get(1))); setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId); Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear(); mCallDataValues.clear();
@ -230,7 +231,7 @@ 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 {
@ -239,12 +240,12 @@ public class Note {
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); : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { } catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e, e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e, e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
}//存储过程中的异常处理 }
} }
return null; return null;
} }

@ -34,7 +34,7 @@ import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private final Note mNote; private Note mNote;
// Note Id // Note Id
private long mNoteId; private long mNoteId;
// Note content // Note content
@ -54,7 +54,7 @@ public class WorkingNote {
private long mFolderId; private long mFolderId;
private final Context mContext; private Context mContext;
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
@ -62,7 +62,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
public static final String[] DATA_PROJECTION = new String[] {//声明DATA_PROJECTION字符串数组 public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -72,7 +72,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
public static final String[] NOTE_PROJECTION = new String[] {//声明NOTE_PROJECTION字符串数组 public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
@ -115,7 +115,6 @@ public class WorkingNote {
} }
// Existing note construct // Existing note construct
//WorkingNote的构造函数
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
@ -124,14 +123,13 @@ public class WorkingNote {
mNote = new Note(); mNote = new Note();
loadNote(); loadNote();
} }
//加载Note
//通过数据库调用query函数找到第一个条目
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
if (cursor != null) {//若存在存储相应信息 if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
@ -141,21 +139,21 @@ 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);
} }
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)) {
@ -167,7 +165,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 {
@ -175,10 +173,9 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); 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, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {//设置相关属性 int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId); note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId); note.setWidgetId(widgetId);
@ -189,10 +186,10 @@ public class WorkingNote {
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
//保存Note
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) {//是否值得保存 if (isWorthSaving()) {
if (!existInDatabase()) {//是否存在数据库中 if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
@ -214,22 +211,24 @@ public class WorkingNote {
return false; return false;
} }
} }
//是否在数据库中存在
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
//是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
//被删除或不在数据库中,内容为空或本地已保存过 if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
return !mIsDeleted && (existInDatabase() || !TextUtils.isEmpty(mContent)) || (existInDatabase() && !mNote.isLocalModified())) {
&& (!existInDatabase() || !mNote.isLocalModified()); return false;
} else {
return true;
}
} }
//设置MnoteSettingStatusListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
//设置AlertDate
//若与data不同则更改并设定NoteValue
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -239,19 +238,17 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
//设定删除标记
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
//设定标记
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
//调用NoteSettingStatusListener的方法
} }
} }
//设定背景颜色
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) {//设定条件id if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
@ -259,10 +256,9 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
//设定检查列表模式
//参数mode
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) {//设定条件mMode!=mode if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -270,91 +266,82 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
} }
//设定WidgetType
//参数type
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) {//设定条件typeWidgetType if (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
} }
} }
//设定Widgetid
//参数id
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) {//设定条件IdWidgetid if (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
} }
} }
//设定WorkingTex
//参数更改的text
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {//设定条件Contenttext内容不同 if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
//调用Note的setTextData方法更改WorkingText
} }
} }
//转变Note的CallData及CallNote信息
//参数String phoneNumberLong callDate
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
//判断是否有时钟题型
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0); return (mAlertDate > 0 ? true : false);
} }
//获取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
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
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
//获取WidgetId
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
//获取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

@ -42,15 +42,7 @@ public class BackupUtils {
private static BackupUtils sInstance; private static BackupUtils sInstance;
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
/*
ynchronized ,线线A
,线BC D()
使synchronized线BC D线A,
,,
synchronized synchronized
*/
if (sInstance == null) { if (sInstance == null) {
//如果当前备份不存在,则新声明一个
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
} }
return sInstance; return sInstance;
@ -61,20 +53,19 @@ public class BackupUtils {
* status * status
*/ */
// Currently, the sdcard is not mounted // Currently, the sdcard is not mounted
//sd卡没有装入手机
public static final int STATE_SD_CARD_UNMOUONTED = 0; 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 final TextExport mTextExport; private TextExport mTextExport;
private BackupUtils(Context context) { //初始化函数 private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
@ -130,7 +121,7 @@ public class BackupUtils {
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 final Context mContext; private Context mContext;
private String mFileName; private String mFileName;
private String mFileDirectory; private String mFileDirectory;
@ -141,8 +132,7 @@ public class BackupUtils {
mFileDirectory = ""; mFileDirectory = "";
} }
private String getFormat(int id) {//获取文本的组成部分 private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
} }
@ -150,7 +140,7 @@ public class BackupUtils {
* 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通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note // Query notes belong to this folder
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
@ -159,13 +149,13 @@ public class BackupUtils {
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// Print note's last modified date ps里保存有这份note的日期 // Print note's last modified date
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);//将文件导出到text exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
} }
notesCursor.close(); notesCursor.close();
@ -181,7 +171,7 @@ public class BackupUtils {
noteId noteId
}, null); }, null);
if (dataCursor != null) {//利用光标来扫描内容区别为callnote和note两种靠ps.printline输出 if (dataCursor != null) {
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
@ -191,7 +181,7 @@ public class BackupUtils {
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));
} }
@ -228,7 +218,7 @@ 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() {//总函数调用上面的exportFolder和exportNote public int exportToText() {
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;
@ -239,7 +229,7 @@ public class BackupUtils {
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,
@ -267,7 +257,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,
@ -307,7 +297,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输出流输出到特定的文件目的就是导出到文件而不是直接输出 ps = new PrintStream(fos);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -324,16 +314,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());//sd卡的存储路径 sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));//文件的存储路径 sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());//filedir存储路径信息 File filedir = new File(sb.toString());
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();
} }

@ -37,7 +37,7 @@ import java.util.HashSet;
public class DataUtils { 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"); Log.d(TAG, "the ids is null");
return true; return true;
@ -47,28 +47,27 @@ public class DataUtils {
return true; return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();//提供一个新的任务列表 ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { 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; continue;
}//如果发现是根文件夹,则不删除 }
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));//用newdelete实现删除功能 .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//主机名 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
//数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行
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); 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, 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, e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false; return false;
} }
@ -78,7 +77,7 @@ public class DataUtils {
values.put(NoteColumns.PARENT_ID, desFolderId); values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); 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);//对需要移动的便签进行数据更新然后用update实现 resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
} }
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
@ -91,23 +90,23 @@ public class DataUtils {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); 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));//通过withAppendedId方法为该Uri加上ID .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId); 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);//applyBatch一次性处理一个操作列表 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
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); 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, 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, e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false; return false;
} }
@ -120,7 +119,7 @@ public class DataUtils {
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);//筛选条件源文件不为trash folder null);
int count = 0; int count = 0;
if(cursor != null) { if(cursor != null) {
@ -128,7 +127,7 @@ public class DataUtils {
try { try {
count = cursor.getInt(0); count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e); Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
cursor.close(); cursor.close();
} }
@ -142,11 +141,11 @@ public class DataUtils {
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);//查询条件type符合且不属于垃圾文件夹 null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空 if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -188,7 +187,6 @@ public class DataUtils {
" 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) {
@ -204,7 +202,7 @@ public class DataUtils {
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?", NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) }, new String[] { String.valueOf(folderId) },
null);//查询条件父id是传入的folderid null);
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null;
if (c != null) { if (c != null) {
@ -213,13 +211,13 @@ public class DataUtils {
do { do {
try { try {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);//0对应的NoteColumns.WIDGET_ID widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);//1对应的NoteColumns.WIDGET_TYPE widget.widgetType = c.getInt(1);
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();
} }
@ -237,7 +235,7 @@ public class DataUtils {
try { try {
return cursor.getString(0); return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e); Log.e(TAG, "Get call number fails " + e.toString());
} finally { } finally {
cursor.close(); cursor.close();
} }
@ -252,14 +250,13 @@ public class DataUtils {
+ CallNote.PHONE_NUMBER + ",?)", + 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 { try {
return cursor.getLong(0);//0对应的CallNote.Note_ID return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e); Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
cursor.close(); cursor.close();
@ -272,7 +269,7 @@ public class DataUtils {
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?", NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)}, new String [] { String.valueOf(noteId)},
null);//查询条件noteId null);
if (cursor != null) { if (cursor != null) {
String snippet = ""; String snippet = "";
@ -285,7 +282,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');

@ -15,7 +15,7 @@
*/ */
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";

@ -13,20 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*使
* R.java
* R.id
* R.drawable 使
* R.layout
* R.menu
* R.String
* R.style 使
* idgetXXX
*
*
* @BG_DEFAULT_COLOR
* BG_DEFAULT_FONT_SIZE
*/
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
@ -174,7 +161,7 @@ public class ResourceParser {
R.style.TextAppearanceLarge, R.style.TextAppearanceLarge,
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.

@ -64,7 +64,7 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
Intent intent = getIntent(); Intent intent = getIntent();
try { try {
mNoteId = Long.parseLong(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
@ -131,11 +131,15 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) { switch (which) {
Intent intent = new Intent(this, NoteEditActivity.class); case DialogInterface.BUTTON_NEGATIVE:
intent.setAction(Intent.ACTION_VIEW); Intent intent = new Intent(this, NoteEditActivity.class);
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.setAction(Intent.ACTION_VIEW);
startActivity(intent); intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
break;
} }
} }

@ -53,7 +53,7 @@ public class AlarmInitReceiver extends BroadcastReceiver {
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE);
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, PendingIntent.FLAG_IMMUTABLE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);

@ -50,9 +50,9 @@ public class DateTimePicker extends FrameLayout {
private final NumberPicker mHourSpinner; private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner; private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner; private final NumberPicker mAmPmSpinner;
private final Calendar mDate; private Calendar mDate;
private final String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm; private boolean mIsAm;
@ -64,7 +64,7 @@ public class DateTimePicker extends FrameLayout {
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
private final NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
@ -73,7 +73,7 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
private final NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false; boolean isDateChanged = false;
@ -115,7 +115,7 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
private final NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue(); int minValue = mMinuteSpinner.getMinValue();
@ -144,7 +144,7 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
private final NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm; mIsAm = !mIsAm;

@ -31,10 +31,10 @@ import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private final Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
private boolean mIs24HourView; private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
private final DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
@ -44,13 +44,16 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker); setView(mDateTimePicker);
mDateTimePicker.setOnDateTimeChangedListener((view, year, month, dayOfMonth, hourOfDay, minute) -> { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
mDate.set(Calendar.YEAR, year); public void onDateTimeChanged(DateTimePicker view, int year, int month,
mDate.set(Calendar.MONTH, month); int dayOfMonth, int hourOfDay, int minute) {
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateTitle(mDate.getTimeInMillis()); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
updateTitle(mDate.getTimeInMillis());
}
}); });
mDate.setTimeInMillis(date); mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0); mDate.set(Calendar.SECOND, 0);
@ -74,7 +77,7 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME;
flag |= DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }

@ -28,9 +28,9 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
public class DropdownMenu { public class DropdownMenu {
private final Button mButton; private Button mButton;
private final PopupMenu mPopupMenu; private PopupMenu mPopupMenu;
private final Menu mMenu; private Menu mMenu;
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;
@ -38,7 +38,11 @@ public class DropdownMenu {
mPopupMenu = new PopupMenu(context, mButton); mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu(); mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mButton.setOnClickListener(v -> mPopupMenu.show()); mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
} }
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {

@ -64,7 +64,7 @@ public class FoldersListAdapter extends CursorAdapter {
} }
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
private final TextView mName; private TextView mName;
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);

@ -24,6 +24,7 @@ import android.app.SearchManager;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Paint; import android.graphics.Paint;
@ -43,6 +44,8 @@ import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
@ -57,6 +60,7 @@ import net.micode.notes.model.WorkingNote.NoteSettingChangedListener;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
import net.micode.notes.tool.ResourceParser.TextAppearanceResources; import net.micode.notes.tool.ResourceParser.TextAppearanceResources;
import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;
import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;
import net.micode.notes.widget.NoteWidgetProvider_2x; import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x; import net.micode.notes.widget.NoteWidgetProvider_4x;
@ -70,7 +74,7 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
private static class HeadViewHolder { private class HeadViewHolder {
public TextView tvModified; public TextView tvModified;
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
@ -305,7 +309,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} else { } else {
mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
} };
} }
@Override @Override
@ -332,13 +336,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& inRangeOfView(mNoteBgColorSelector, ev)) { && !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
} }
if (mFontSizeSelector.getVisibility() == View.VISIBLE if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& inRangeOfView(mFontSizeSelector, ev)) { && !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
@ -350,10 +354,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
int x = location[0]; int x = location[0];
int y = location[1]; int y = location[1];
return ev.getX() < x if (ev.getX() < x
|| ev.getX() > (x + view.getWidth()) || ev.getX() > (x + view.getWidth())
|| ev.getY() < y || ev.getY() < y
|| ev.getY() > (y + view.getHeight()); || ev.getY() > (y + view.getHeight())) {
return false;
}
return true;
} }
private void initResources() { private void initResources() {
@ -376,7 +383,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
for (int id : sFontSizeBtnsMap.keySet()) { for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id); View view = findViewById(id);
view.setOnClickListener(this); view.setOnClickListener(this);
} };
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/** /**
@ -423,7 +430,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); - View.VISIBLE);
} else if (sBgSelectorBtnsMap.containsKey(id)) { } else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE); View.GONE);
@ -510,9 +517,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_note)); builder.setMessage(getString(R.string.alert_message_delete_note));
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
(dialog, which) -> { new DialogInterface.OnClickListener() {
deleteCurrentNote(); public void onClick(DialogInterface dialog, int which) {
finish(); deleteCurrentNote();
finish();
}
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
@ -546,7 +555,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private void setReminder() { private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener((dialog, date) -> mWorkingNote.setAlertDate(date , true)); d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
public void OnDateTimeSet(AlertDialog dialog, long date) {
mWorkingNote.setAlertDate(date , true);
}
});
d.show(); d.show();
} }
@ -610,7 +623,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {
Intent intent = new Intent(this, AlarmReceiver.class); Intent intent = new Intent(this, AlarmReceiver.class);
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
showAlertHeader(); showAlertHeader();
if(!set) { if(!set) {
@ -717,11 +730,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
cb.setOnCheckedChangeListener((buttonView, isChecked) -> { cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
if (isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); if (isChecked) {
} else { edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); } else {
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
}
} }
}); });

@ -16,7 +16,6 @@
package net.micode.notes.ui; package net.micode.notes.ui;
import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.graphics.Rect; import android.graphics.Rect;
import android.text.Layout; import android.text.Layout;
@ -100,21 +99,23 @@ public class NoteEditText extends EditText {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
@SuppressLint("ClickableViewAccessibility")
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { switch (event.getAction()) {
int x = (int) event.getX(); case MotionEvent.ACTION_DOWN:
int y = (int) event.getY();
x -= getTotalPaddingLeft(); int x = (int) event.getX();
y -= getTotalPaddingTop(); int y = (int) event.getY();
x += getScrollX(); x -= getTotalPaddingLeft();
y += getScrollY(); y -= getTotalPaddingTop();
x += getScrollX();
Layout layout = getLayout(); y += getScrollY();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x); Layout layout = getLayout();
Selection.setSelection(getText(), off); int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
break;
} }
return super.onTouchEvent(event); return super.onTouchEvent(event);
@ -169,7 +170,11 @@ public class NoteEditText extends EditText {
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
mOnTextViewChangeListener.onTextChange(mIndex, focused || !TextUtils.isEmpty(getText())); if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
}
} }
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect);
} }
@ -187,7 +192,7 @@ public class NoteEditText extends EditText {
if (urls.length == 1) { if (urls.length == 1) {
int defaultResId = 0; int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) { for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().contains(schema)) { if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema); defaultResId = sSchemaActionResMap.get(schema);
break; break;
} }
@ -198,10 +203,12 @@ public class NoteEditText extends EditText {
} }
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
item -> { new OnMenuItemClickListener() {
// goto a new intent public boolean onMenuItemClick(MenuItem item) {
urls[0].onClick(NoteEditText.this); // goto a new intent
return true; urls[0].onClick(NoteEditText.this);
return true;
}
}); });
} }
} }

@ -55,18 +55,18 @@ public class NoteItemData {
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
private final long mId; private long mId;
private final long mAlertDate; private long mAlertDate;
private final int mBgColorId; private int mBgColorId;
private final long mCreatedDate; private long mCreatedDate;
private final boolean mHasAttachment; private boolean mHasAttachment;
private final long mModifiedDate; private long mModifiedDate;
private final int mNotesCount; private int mNotesCount;
private final long mParentId; private long mParentId;
private String mSnippet; private String mSnippet;
private final int mType; private int mType;
private final int mWidgetId; private int mWidgetId;
private final int mWidgetType; private int mWidgetType;
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
@ -81,7 +81,7 @@ public class NoteItemData {
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
@ -110,8 +110,8 @@ public class NoteItemData {
} }
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast(); mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst(); mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false;

@ -16,7 +16,6 @@
package net.micode.notes.ui; package net.micode.notes.ui;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Dialog; import android.app.Dialog;
@ -94,7 +93,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
} };
private ListEditState mState; private ListEditState mState;
@ -210,7 +209,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
@SuppressLint("ClickableViewAccessibility")
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
@ -260,10 +258,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mDropDownMenu = new DropdownMenu(NotesListActivity.this, mDropDownMenu = new DropdownMenu(NotesListActivity.this,
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(item -> { mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); public boolean onMenuItemClick(MenuItem item) {
updateMenu(); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
return true; updateMenu();
return true;
}
}); });
return true; return true;
} }
@ -326,7 +327,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setMessage(getString(R.string.alert_message_delete_notes, builder.setMessage(getString(R.string.alert_message_delete_notes,
mNotesListAdapter.getSelectedCount())); mNotesListAdapter.getSelectedCount()));
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
(dialog, which) -> batchDelete()); new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
batchDelete();
}
});
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
break; break;
@ -342,7 +348,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private class NewNoteOnTouchListener implements OnTouchListener { private class NewNoteOnTouchListener implements OnTouchListener {
@SuppressLint("ClickableViewAccessibility")
public boolean onTouch(View v, MotionEvent event) { public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: { case MotionEvent.ACTION_DOWN: {
@ -401,7 +406,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return false; return false;
} }
} };
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
@ -440,16 +445,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
builder.setAdapter(adapter, (dialog, which) -> { builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); public void onClick(DialogInterface dialog, int which) {
Toast.makeText( DataUtils.batchMoveToFolder(mContentResolver,
NotesListActivity.this, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
getString(R.string.format_move_notes_to_folder, Toast.makeText(
mNotesListAdapter.getSelectedCount(), NotesListActivity.this,
adapter.getFolderName(NotesListActivity.this, which)), getString(R.string.format_move_notes_to_folder,
Toast.LENGTH_SHORT).show(); mNotesListAdapter.getSelectedCount(),
mModeCallBack.finishActionMode(); adapter.getFolderName(NotesListActivity.this, which)),
Toast.LENGTH_SHORT).show();
mModeCallBack.finishActionMode();
}
}); });
builder.show(); builder.show();
} }
@ -463,7 +471,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private void batchDelete() { private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
@SuppressLint("StaticFieldLeak")
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) { if (!isSyncMode()) {
@ -551,8 +558,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
public void onClick(View v) { public void onClick(View v) {
if (v.getId() == R.id.btn_new_note) { switch (v.getId()) {
createNewNote(); case R.id.btn_new_note:
createNewNote();
break;
default:
break;
} }
} }
@ -587,37 +598,43 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> hideSoftInput(etName)); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName);
}
});
final Dialog dialog = builder.setView(view).show(); final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1); final Button positive = (Button)dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(v -> { positive.setOnClickListener(new OnClickListener() {
hideSoftInput(etName); public void onClick(View v) {
String name = etName.getText().toString(); hideSoftInput(etName);
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { String name = etName.getText().toString();
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
Toast.LENGTH_LONG).show(); Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
etName.setSelection(0, etName.length()); Toast.LENGTH_LONG).show();
return; etName.setSelection(0, etName.length());
} return;
if (!create) { }
if (!TextUtils.isEmpty(name)) { if (!create) {
if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId())
});
}
} else if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1); mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId())
});
} }
} else if (!TextUtils.isEmpty(name)) { dialog.dismiss();
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
} }
dialog.dismiss();
}); });
if (TextUtils.isEmpty(etName.getText())) { if (TextUtils.isEmpty(etName.getText())) {
@ -633,7 +650,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
public void onTextChanged(CharSequence s, int start, int before, int count) { public void onTextChanged(CharSequence s, int start, int before, int count) {
positive.setEnabled(!TextUtils.isEmpty(etName.getText())); if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
} else {
positive.setEnabled(true);
}
} }
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -721,7 +742,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder));
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
(dialog, which) -> deleteFolder(mFocusNoteDataItem.getId())); new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteFolder(mFocusNoteDataItem.getId());
}
});
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
break; break;

@ -33,15 +33,15 @@ import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private final Context mContext; private Context mContext;
private final HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; private int mNotesCount;
private boolean mChoiceMode; private boolean mChoiceMode;
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
} };
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
@ -92,7 +92,7 @@ public class NotesListAdapter extends CursorAdapter {
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position)) { if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position); Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
@ -108,7 +108,7 @@ public class NotesListAdapter extends CursorAdapter {
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position)) { if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position); Cursor c = (Cursor) getItem(position);
if (c != null) { if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
@ -136,7 +136,7 @@ public class NotesListAdapter extends CursorAdapter {
Iterator<Boolean> iter = values.iterator(); Iterator<Boolean> iter = values.iterator();
int count = 0; int count = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
if (iter.next()) { if (true == iter.next()) {
count++; count++;
} }
} }

@ -31,12 +31,12 @@ import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private final ImageView mAlert; private ImageView mAlert;
private final TextView mTitle; private TextView mTitle;
private final TextView mTime; private TextView mTime;
private final TextView mCallName; private TextView mCallName;
private NoteItemData mItemData; private NoteItemData mItemData;
private final CheckBox mCheckBox; private CheckBox mCheckBox;
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);

@ -18,6 +18,7 @@ package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentValues; import android.content.ContentValues;
@ -34,6 +35,7 @@ import android.preference.PreferenceCategory;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
@ -129,22 +131,24 @@ public class NotesPreferenceActivity extends PreferenceActivity {
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(preference -> { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
if (!GTaskSyncService.isSyncing()) { public boolean onPreferenceClick(Preference preference) {
if (TextUtils.isEmpty(defaultAccount)) { if (!GTaskSyncService.isSyncing()) {
// the first time to set account if (TextUtils.isEmpty(defaultAccount)) {
showSelectAccountAlertDialog(); // the first time to set account
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();
}
} else { } else {
// if the account has already been set, we need to promp Toast.makeText(NotesPreferenceActivity.this,
// user about the risk R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
showChangeAccountConfirmAlertDialog(); .show();
} }
} else { return true;
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
} }
return true;
}); });
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
@ -157,10 +161,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
// set button state // set button state
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(v -> GTaskSyncService.cancelSync(NotesPreferenceActivity.this)); syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(v -> GTaskSyncService.startSync(NotesPreferenceActivity.this)); syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
@ -216,10 +228,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
items[index++] = account.name; items[index++] = account.name;
} }
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
(dialog, which) -> { new DialogInterface.OnClickListener() {
setSyncAccount(itemMapping[which].toString()); public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); setSyncAccount(itemMapping[which].toString());
refreshUI(); dialog.dismiss();
refreshUI();
}
}); });
} }
@ -227,14 +241,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(v -> { addAccountView.setOnClickListener(new View.OnClickListener() {
mHasAddedAccount = true; public void onClick(View v) {
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); mHasAddedAccount = true;
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
"gmail-ls" intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
}); "gmail-ls"
startActivityForResult(intent, -1); });
dialog.dismiss(); startActivityForResult(intent, -1);
dialog.dismiss();
}
}); });
} }
@ -254,12 +270,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
}; };
dialogBuilder.setItems(menuItemArray, (dialog, which) -> { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
if (which == 0) { public void onClick(DialogInterface dialog, int which) {
showSelectAccountAlertDialog(); if (which == 0) {
} else if (which == 1) { showSelectAccountAlertDialog();
removeSyncAccount(); } else if (which == 1) {
refreshUI(); removeSyncAccount();
refreshUI();
}
} }
}); });
dialogBuilder.show(); dialogBuilder.show();
@ -285,11 +303,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // clean up local gtask related info
new Thread(() -> { new Thread(new Runnable() {
ContentValues values = new ContentValues(); public void run() {
values.put(NoteColumns.GTASK_ID, ""); ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.GTASK_ID, "");
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start(); }).start();
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
@ -310,11 +330,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
// clean up local gtask related info // clean up local gtask related info
new Thread(() -> { new Thread(new Runnable() {
ContentValues values = new ContentValues(); public void run() {
values.put(NoteColumns.GTASK_ID, ""); ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.GTASK_ID, "");
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start(); }).start();
} }
@ -353,12 +375,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) { switch (item.getItemId()) {
Intent intent = new Intent(this, NotesListActivity.class); case android.R.id.home:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Intent intent = new Intent(this, NotesListActivity.class);
startActivity(intent); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return true; startActivity(intent);
return true;
default:
return false;
} }
return false;
} }
} }

@ -49,11 +49,11 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int appWidgetId : appWidgetIds) { for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI, context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values, values,
NoteColumns.WIDGET_ID + "=?", NoteColumns.WIDGET_ID + "=?",
new String[]{String.valueOf(appWidgetId)}); new String[] { String.valueOf(appWidgetIds[i])});
} }
} }
@ -71,22 +71,19 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
/** for (int i = 0; i < appWidgetIds.length; i++) {
* Generate the pending intent to start host for the widget if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
*/
for (int appWidgetId : appWidgetIds) {
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context); int bgId = ResourceParser.getDefaultBgId(context);
String snippet = ""; String snippet = "";
Intent intent = new Intent(context, NoteEditActivity.class); Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetId); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
Cursor c = getNoteWidgetInfo(context, appWidgetId); Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) { if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) { if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetId); Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close(); c.close();
return; return;
} }
@ -113,16 +110,16 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
if (privacyMode) { if (privacyMode) {
rv.setTextViewText(R.id.widget_text, rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode)); context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetId, new Intent( pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
rv.setTextViewText(R.id.widget_text, snippet); rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent.FLAG_UPDATE_CURRENT);
} }
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
} }
} }
} }

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 245 B

After

Width:  |  Height:  |  Size: 245 B

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 443 B

After

Width:  |  Height:  |  Size: 443 B

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Before

Width:  |  Height:  |  Size: 554 KiB

After

Width:  |  Height:  |  Size: 554 KiB

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save