/
Task.java
1277 lines (1163 loc) · 43.9 KB
/
Task.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015 Jonas Kalderstam.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nononsenseapps.notepad.data.model.sql;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.text.format.Time;
import com.nononsenseapps.notepad.data.local.sql.LegacyDBHelper;
import com.nononsenseapps.notepad.data.local.sql.MyContentProvider;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.InvalidParameterException;
import java.util.Calendar;
/**
* An object that represents the task information contained in the database.
* Provides convenience methods for moving items.
*/
public class Task extends DAO {
// Used to separate tasks with due dates from completed and from tasks with
// no date
public static final String SECRET_TYPEID = "secret_typeid";
public static final String SECRET_TYPEID2 = "secret_typeid2";
// SQL convention says Table name should be "singular"
public static final String TABLE_NAME = "task";
public static final String DELETE_TABLE_NAME = "deleted_task";
public static final String FTS3_DELETE_TABLE_NAME = "fts3_deleted_task";
public static final String HISTORY_TABLE_NAME = "history";
private static final String SECTIONED_DATE_VIEW = "sectioned_date_view";
public static final String FTS3_TABLE_NAME = "fts3_task";
private static final String TAG = "Task";
public static String getSECTION_DATE_VIEW_NAME(final String listId) {
// listId CAN be null. Hence the string concat hack
return new StringBuilder().append(SECTIONED_DATE_VIEW).append("_")
.append("" + listId).toString();
}
// Used in sectioned view date
static final String FAR_FUTURE = "strftime('%s','3999-01-01') * 1000";
public static final String OVERDUE = "strftime('%s', '1970-01-01') * 1000";
// Today should be from NOW...
public static final String TODAY_START = "strftime('%s','now', 'utc') * 1000";
// static final String TODAY_START =
// "strftime('%s','now','localtime','start of day', 'utc') * 1000";
public static final String TODAY_PLUS(final int offset) {
return "strftime('%s','now','localtime','+" + Integer.toString(offset)
+ " days','start of day', 'utc') * 1000";
}
// Code used to decode title of date header
public static final String HEADER_KEY_TODAY = "today+0";
public static final String HEADER_KEY_PLUS1 = "today+1";
public static final String HEADER_KEY_PLUS2 = "today+2";
public static final String HEADER_KEY_PLUS3 = "today+3";
public static final String HEADER_KEY_PLUS4 = "today+4";
public static final String HEADER_KEY_OVERDUE = "overdue";
public static final String HEADER_KEY_LATER = "later";
public static final String HEADER_KEY_NODATE = "nodate";
public static final String HEADER_KEY_COMPLETE = "complete";
public static final String CONTENT_TYPE = "vnd.android.cursor.item/vnd.nononsenseapps.note";
public static final Uri URI = Uri.withAppendedPath(
Uri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),
TABLE_NAME);
public static Uri getUri(final long id) {
return Uri.withAppendedPath(URI, Long.toString(id));
}
public static final int BASEURICODE = 201;
public static final int BASEITEMCODE = 202;
public static final int DELETEDQUERYCODE = 209;
public static final int DELETEDITEMCODE = 210;
public static final int SECTIONEDDATEQUERYCODE = 211;
public static final int SECTIONEDDATEITEMCODE = 212;
public static final int HISTORYQUERYCODE = 213;
public static final int MOVEITEMLEFTCODE = 214;
public static final int MOVEITEMRIGHTCODE = 215;
// Legacy support, these also need to use legacy projections
public static final int LEGACYBASEURICODE = 221;
public static final int LEGACYBASEITEMCODE = 222;
public static final int LEGACYVISIBLEURICODE = 223;
public static final int LEGACYVISIBLEITEMCODE = 224;
// Search URI
public static final int SEARCHCODE = 299;
public static final int SEARCHSUGGESTIONSCODE = 298;
public static void addMatcherUris(UriMatcher sURIMatcher) {
sURIMatcher
.addURI(MyContentProvider.AUTHORITY, TABLE_NAME, BASEURICODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/#",
BASEITEMCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ MOVEITEMLEFT + "/#", MOVEITEMLEFTCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ MOVEITEMRIGHT + "/#", MOVEITEMRIGHTCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ DELETEDQUERY, DELETEDQUERYCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ DELETEDQUERY + "/#", DELETEDITEMCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ SECTIONED_DATE_VIEW, SECTIONEDDATEQUERYCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ SECTIONED_DATE_VIEW + "/#", SECTIONEDDATEITEMCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + "/"
+ HISTORY_TABLE_NAME, HISTORYQUERYCODE);
// Legacy URIs
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
LegacyDBHelper.NotePad.Notes.NOTES, LEGACYBASEURICODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
LegacyDBHelper.NotePad.Notes.NOTES + "/#", LEGACYBASEITEMCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
LegacyDBHelper.NotePad.Notes.VISIBLE_NOTES,
LEGACYVISIBLEURICODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
LegacyDBHelper.NotePad.Notes.VISIBLE_NOTES + "/#",
LEGACYVISIBLEITEMCODE);
// Search URI
sURIMatcher.addURI(MyContentProvider.AUTHORITY, FTS3_TABLE_NAME,
SEARCHCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
SearchManager.SUGGEST_URI_PATH_QUERY, SEARCHSUGGESTIONSCODE);
sURIMatcher.addURI(MyContentProvider.AUTHORITY,
SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
SEARCHSUGGESTIONSCODE);
}
public static final String TARGETPOS = "targetpos";
private static final String MOVEITEMLEFT = "moveitemleft";
private static final String MOVEITEMRIGHT = "moveitemright";
private static final String DELETEDQUERY = "deletedquery";
// Special URI to look at backup table
public static final Uri URI_DELETED_QUERY = Uri.withAppendedPath(URI,
DELETEDQUERY);
// Query the view with date section headers
public static final Uri URI_SECTIONED_BY_DATE = Uri.withAppendedPath(URI,
SECTIONED_DATE_VIEW);
// Query for history of tasks
public static final Uri URI_TASK_HISTORY = Uri.withAppendedPath(URI,
HISTORY_TABLE_NAME);
// Search URI
public static final Uri URI_SEARCH = Uri.withAppendedPath(
Uri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),
FTS3_TABLE_NAME);
// Special URI to use when a move is requested
// public static final Uri URI_WRITE_MOVESUBTREE = Uri.withAppendedPath(URI,
// MOVESUBTREE);
private static final Uri URI_WRITE_MOVEITEMLEFT = Uri.withAppendedPath(URI,
MOVEITEMLEFT);
private static final Uri URI_WRITE_MOVEITEMRIGHT = Uri.withAppendedPath(
URI, MOVEITEMRIGHT);
// public Uri getMoveSubTreeUri() {
// if (_id < 1) {
// throw new InvalidParameterException(
// "_ID of this object is not valid");
// }
// return Uri.withAppendedPath(URI_WRITE_MOVESUBTREE, Long.toString(_id));
// }
private Uri getMoveItemLeftUri() {
if (_id < 1) {
throw new InvalidParameterException(
"_ID of this object is not valid");
}
return Uri.withAppendedPath(URI_WRITE_MOVEITEMLEFT, Long.toString(_id));
}
private Uri getMoveItemRightUri() {
if (_id < 1) {
throw new InvalidParameterException(
"_ID of this object is not valid");
}
return Uri
.withAppendedPath(URI_WRITE_MOVEITEMRIGHT, Long.toString(_id));
}
public static int delete(final long id, Context context) {
if (id > 0) {
return context.getContentResolver()
.delete(Uri.withAppendedPath(Uri.withAppendedPath(
Uri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),
TABLE_NAME), Long.toString(id)),
null,
null);
}
throw new IllegalArgumentException("Can only delete positive ids");
}
public static class Columns implements BaseColumns {
private Columns() {
}
public static final String TITLE = "title";
public static final String NOTE = "note";
public static final String DBLIST = "dblist";
public static final String COMPLETED = "completed";
public static final String DUE = "due";
public static final String UPDATED = "updated";
public static final String LOCKED = "locked";
public static final String LEFT = "lft";
public static final String RIGHT = "rgt";
public static final String[] FIELDS = { _ID, TITLE, NOTE, COMPLETED,
DUE, UPDATED, LEFT, RIGHT, DBLIST, LOCKED };
public static final String[] FIELDS_NO_ID = { TITLE, NOTE, COMPLETED,
DUE, UPDATED, LEFT, RIGHT, DBLIST, LOCKED };
public static final String[] SHALLOWFIELDS = { _ID, TITLE, NOTE,
DBLIST, COMPLETED, DUE, UPDATED, LOCKED };
public static final String TRIG_DELETED = "deletedtime";
public static final String HIST_TASK_ID = "taskid";
// Used to read the table. Deleted field set by database
public static final String[] DELETEFIELDS = { _ID, TITLE, NOTE,
COMPLETED, DUE, DBLIST, TRIG_DELETED };
// Used in trigger creation
private static final String[] DELETEFIELDS_TRIGGER = { TITLE, NOTE,
COMPLETED, DUE, DBLIST };
// accessible fields in history table
public static final String[] HISTORY_COLUMNS = { Columns.HIST_TASK_ID,
Columns.TITLE, Columns.NOTE };
public static final String[] HISTORY_COLUMNS_UPDATED = { Columns.HIST_TASK_ID,
Columns.TITLE, Columns.NOTE, Columns.UPDATED };
}
public static final String CREATE_TABLE = new StringBuilder("CREATE TABLE ")
.append(TABLE_NAME)
.append("(")
.append(Columns._ID)
.append(" INTEGER PRIMARY KEY,")
.append(Columns.TITLE)
.append(" TEXT NOT NULL DEFAULT '',")
.append(Columns.NOTE)
.append(" TEXT NOT NULL DEFAULT '',")
// These are all msec times
.append(Columns.COMPLETED)
.append(" INTEGER DEFAULT NULL,")
.append(Columns.UPDATED)
.append(" INTEGER DEFAULT NULL,")
.append(Columns.DUE)
.append(" INTEGER DEFAULT NULL,")
// boolean, 1 for locked, unlocked otherwise
.append(Columns.LOCKED)
.append(" INTEGER NOT NULL DEFAULT 0,")
// position stuff
.append(Columns.LEFT)
.append(" INTEGER NOT NULL DEFAULT 1,")
.append(Columns.RIGHT)
.append(" INTEGER NOT NULL DEFAULT 2,")
.append(Columns.DBLIST)
.append(" INTEGER NOT NULL,")
// Positions must be positive and ordered!
.append(" CHECK(")
.append(Columns.LEFT)
.append(" > 0), ")
.append(" CHECK(")
.append(Columns.RIGHT)
.append(" > 1), ")
// Each side's value should be unique in it's list
// Handled in trigger
// ).append(" UNIQUE(").append(Columns.LEFT).append(", ").append(Columns.DBLIST).append(")"
// ).append(" UNIQUE(").append(Columns.RIGHT).append(", ").append(Columns.DBLIST).append(")"
// Foreign key for list
.append("FOREIGN KEY(").append(Columns.DBLIST)
.append(") REFERENCES ").append(TaskList.TABLE_NAME).append("(")
.append(TaskList.Columns._ID).append(") ON DELETE CASCADE")
.append(")")
.toString();
// Delete table has no constraints. In fact, list values and positions
// should not even be thought of as valid.
public static final String CREATE_DELETE_TABLE = new StringBuilder(
"CREATE TABLE ").append(DELETE_TABLE_NAME).append("(")
.append(Columns._ID).append(" INTEGER PRIMARY KEY,")
.append(Columns.TITLE).append(" TEXT NOT NULL DEFAULT '',")
.append(Columns.NOTE).append(" TEXT NOT NULL DEFAULT '',")
.append(Columns.COMPLETED).append(" INTEGER DEFAULT NULL,")
.append(Columns.DUE).append(" INTEGER DEFAULT NULL,")
.append(Columns.DBLIST).append(" INTEGER DEFAULT NULL,")
.append(Columns.TRIG_DELETED)
.append(" TIMESTAMP NOT NULL DEFAULT current_timestamp")
.append(")").toString();
// Every change to a note gets saved here
public static final String CREATE_HISTORY_TABLE = new StringBuilder(
"CREATE TABLE ").append(HISTORY_TABLE_NAME).append("(")
.append(Columns._ID).append(" INTEGER PRIMARY KEY,")
.append(Columns.HIST_TASK_ID).append(" INTEGER NOT NULL,")
.append(Columns.TITLE).append(" TEXT NOT NULL DEFAULT '',")
.append(Columns.NOTE).append(" TEXT NOT NULL DEFAULT '',")
.append(Columns.UPDATED)
.append(" TIMESTAMP NOT NULL DEFAULT current_timestamp,")
.append(" FOREIGN KEY(").append(Columns.HIST_TASK_ID)
.append(" ) REFERENCES ").append(TABLE_NAME).append(" ( ")
.append(Columns._ID).append(") ON DELETE CASCADE ").append(" ) ")
.toString();
static final String HISTORY_TRIGGER_BODY = new StringBuilder(
" INSERT INTO ")
.append(HISTORY_TABLE_NAME)
.append(" (")
.append(arrayToCommaString(Columns.HISTORY_COLUMNS))
.append(")")
.append(" VALUES (")
.append(arrayToCommaString("new.", new String[] { Columns._ID,
Columns.TITLE, Columns.NOTE })).append(");").toString();
public static final String HISTORY_UPDATE_TRIGGER_NAME = "trigger_update_" + HISTORY_TABLE_NAME;
public static final String CREATE_HISTORY_UPDATE_TRIGGER = new StringBuilder(
"CREATE TRIGGER ").append(HISTORY_UPDATE_TRIGGER_NAME)
.append(" AFTER UPDATE OF ")
.append(arrayToCommaString(new String[] { Columns.TITLE,
Columns.NOTE })).append(" ON ").append(TABLE_NAME)
.append(" WHEN old.")
.append(Columns.TITLE).append(" IS NOT new.")
.append(Columns.TITLE).append(" OR old.")
.append(Columns.NOTE).append(" IS NOT new.")
.append(Columns.NOTE)
.append(" BEGIN ").append(HISTORY_TRIGGER_BODY).append(" END;")
.toString();
public static final String CREATE_HISTORY_INSERT_TRIGGER = new StringBuilder(
"CREATE TRIGGER trigger_insert_").append(HISTORY_TABLE_NAME)
.append(" AFTER INSERT ON ").append(TABLE_NAME).append(" BEGIN ")
.append(HISTORY_TRIGGER_BODY).append(" END;").toString();
// Delete search table
public static final String CREATE_FTS3_DELETE_TABLE = "CREATE VIRTUAL TABLE "
+ FTS3_DELETE_TABLE_NAME
+ " USING FTS3("
+ Columns._ID
+ ", "
+ Columns.TITLE + ", " + Columns.NOTE + ");";
public static final String CREATE_FTS3_DELETED_INSERT_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER deletedtask_fts3_insert AFTER INSERT ON ")
.append(DELETE_TABLE_NAME)
.append(" BEGIN ")
.append(" INSERT INTO ")
.append(FTS3_DELETE_TABLE_NAME)
.append(" (")
.append(arrayToCommaString(Columns._ID, Columns.TITLE, Columns.NOTE))
.append(") VALUES (")
.append(arrayToCommaString("new.", new String[] { Columns._ID,
Columns.TITLE, Columns.NOTE })).append(");")
.append(" END;").toString();
public static final String CREATE_FTS3_DELETED_UPDATE_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER deletedtask_fts3_update AFTER UPDATE OF ")
.append(arrayToCommaString(new String[] { Columns.TITLE,
Columns.NOTE })).append(" ON ").append(DELETE_TABLE_NAME)
.append(" BEGIN ").append(" UPDATE ")
.append(FTS3_DELETE_TABLE_NAME).append(" SET ")
.append(Columns.TITLE).append(" = new.").append(Columns.TITLE)
.append(",").append(Columns.NOTE).append(" = new.")
.append(Columns.NOTE).append(" WHERE ").append(Columns._ID)
.append(" IS new.").append(Columns._ID).append(";").append(" END;")
.toString();
public static final String CREATE_FTS3_DELETED_DELETE_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER deletedtask_fts3_delete AFTER DELETE ON ")
.append(DELETE_TABLE_NAME).append(" BEGIN ")
.append(" DELETE FROM ").append(FTS3_DELETE_TABLE_NAME)
.append(" WHERE ").append(Columns._ID).append(" IS old.")
.append(Columns._ID).append(";").append(" END;").toString();
// Search table
public static final String CREATE_FTS3_TABLE = "CREATE VIRTUAL TABLE "
+ FTS3_TABLE_NAME + " USING FTS3(" + Columns._ID + ", "
+ Columns.TITLE + ", " + Columns.NOTE + ");";
public static final String CREATE_FTS3_INSERT_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER task_fts3_insert AFTER INSERT ON ")
.append(TABLE_NAME)
.append(" BEGIN ")
.append(" INSERT INTO ")
.append(FTS3_TABLE_NAME)
.append(" (")
.append(arrayToCommaString(Columns._ID, Columns.TITLE, Columns.NOTE))
.append(") VALUES (")
.append(arrayToCommaString("new.", new String[] { Columns._ID,
Columns.TITLE, Columns.NOTE })).append(");")
.append(" END;").toString();
public static final String CREATE_FTS3_UPDATE_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER task_fts3_update AFTER UPDATE OF ")
.append(arrayToCommaString(new String[] { Columns.TITLE,
Columns.NOTE })).append(" ON ").append(TABLE_NAME)
.append(" BEGIN ").append(" UPDATE ").append(FTS3_TABLE_NAME)
.append(" SET ").append(Columns.TITLE).append(" = new.")
.append(Columns.TITLE).append(",").append(Columns.NOTE)
.append(" = new.").append(Columns.NOTE).append(" WHERE ")
.append(Columns._ID).append(" IS new.").append(Columns._ID)
.append(";").append(" END;").toString();
public static final String CREATE_FTS3_DELETE_TRIGGER = new StringBuilder()
.append("CREATE TRIGGER task_fts3_delete AFTER DELETE ON ")
.append(TABLE_NAME).append(" BEGIN ").append(" DELETE FROM ")
.append(FTS3_TABLE_NAME).append(" WHERE ").append(Columns._ID)
.append(" IS old.").append(Columns._ID).append(";").append(" END;")
.toString();
/**
* This is a view which returns the tasks in the specified list with headers
* suitable for dates, if any tasks would be sorted under them. Provider
* hardcodes the sort order for this.
*
* if listId is null, will return for all lists
*/
public static final String CREATE_SECTIONED_DATE_VIEW(final String listId) {
final String sListId = listId == null ? " NOT NULL " : "'" + listId
+ "'";
return new StringBuilder()
.append("CREATE TEMP VIEW IF NOT EXISTS ")
.append(getSECTION_DATE_VIEW_NAME(listId))
// Tasks WITH dates NOT completed, secret 0
.append(" AS SELECT ")
.append(arrayToCommaString(Columns.FIELDS))
.append(",0")
.append(" AS ")
.append(SECRET_TYPEID)
.append(",1")
.append(" AS ")
.append(SECRET_TYPEID2)
.append(" FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS null ")
.append(" AND ")
.append(Columns.DUE)
.append(" IS NOT null ")
.append(" UNION ALL ")
// Tasks NO dates NOT completed, secret 1
.append(" SELECT ")
.append(arrayToCommaString(Columns.FIELDS))
.append(",1")
.append(" AS ")
.append(SECRET_TYPEID)
.append(",1")
.append(" AS ")
.append(SECRET_TYPEID2)
.append(" FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS null ")
.append(" AND ")
.append(Columns.DUE)
.append(" IS null ")
.append(" UNION ALL ")
// Tasks completed, secret 2 + 1
.append(" SELECT ")
.append(arrayToCommaString(Columns.FIELDS))
.append(",3")
.append(" AS ")
.append(SECRET_TYPEID)
.append(",1")
.append(" AS ")
.append(SECRET_TYPEID2)
.append(" FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NOT null ")
// TODAY
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_START, Columns.TITLE,
HEADER_KEY_TODAY, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(TODAY_START)
.append(" AND ")
.append(TODAY_PLUS(1))
.append(") ")
// TOMORROW (Today + 1)
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_PLUS(1), Columns.TITLE,
HEADER_KEY_PLUS1, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(TODAY_PLUS(1))
.append(" AND ")
.append(TODAY_PLUS(2))
.append(") ")
// Today + 2
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_PLUS(2), Columns.TITLE,
HEADER_KEY_PLUS2, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(TODAY_PLUS(2))
.append(" AND ")
.append(TODAY_PLUS(3))
.append(") ")
// Today + 3
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_PLUS(3), Columns.TITLE,
HEADER_KEY_PLUS3, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(TODAY_PLUS(3))
.append(" AND ")
.append(TODAY_PLUS(4))
.append(") ")
// Today + 4
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_PLUS(4), Columns.TITLE,
HEADER_KEY_PLUS4, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(TODAY_PLUS(4))
.append(" AND ")
.append(TODAY_PLUS(5))
.append(") ")
// Overdue (0)
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, OVERDUE, Columns.TITLE,
HEADER_KEY_OVERDUE, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" BETWEEN ")
.append(OVERDUE)
.append(" AND ")
.append(TODAY_START)
.append(") ")
// Later
.append(" UNION ALL ")
.append(" SELECT '-1',")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, TODAY_PLUS(5), Columns.TITLE,
HEADER_KEY_LATER, Columns.DBLIST, listId))
.append(",0,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.COMPLETED)
.append(" IS NULL ")
.append(" AND ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" >= ")
.append(TODAY_PLUS(5))
.append(") ")
// No date
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, "null", Columns.TITLE, HEADER_KEY_NODATE,
Columns.DBLIST, listId))
.append(",1,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ")
.append(TABLE_NAME)
.append(" WHERE ")
.append(Columns.DBLIST)
.append(" IS ")
.append(sListId)
.append(" AND ")
.append(Columns.DUE)
.append(" IS null ")
.append(" AND ")
.append(Columns.COMPLETED)
.append(" IS null ")
.append(") ")
// Complete, overdue to catch all
// Set complete time to 1
.append(" UNION ALL ")
.append(" SELECT -1,")
.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,
Columns.DUE, OVERDUE, Columns.COMPLETED, "1",
Columns.TITLE, HEADER_KEY_COMPLETE, Columns.DBLIST,
listId))
.append(",2,0")
// Only show header if there are tasks under it
.append(" WHERE EXISTS(SELECT _ID FROM ").append(TABLE_NAME)
.append(" WHERE ").append(Columns.DBLIST).append(" IS ")
.append(sListId).append(" AND ").append(Columns.COMPLETED)
.append(" IS NOT null ").append(") ")
.append(";").toString();
}
public String title = null;
public String note = null;
// All milliseconds since 1970-01-01 UTC
public Long completed = null;
public Long due = null;
public Long updated = null;
// converted from integer
public boolean locked = false;
// position stuff
public Long left = null;
public Long right = null;
public Long dblist = null;
public Task() {
}
/**
* Resets id and position values
*/
public void resetForInsertion() {
_id = -1;
left = null;
right = null;
}
/**
* Set task as completed. Returns the time stamp that is set.
*/
public Long setAsCompleted() {
final Time time = new Time(Time.TIMEZONE_UTC);
time.setToNow();
completed = new Time().toMillis(false);
return completed;
}
/**
* Set first line as title, rest as note.
*
* @param text
*/
public void setText(final String text) {
int titleEnd = text.indexOf("\n");
if (titleEnd < 0) {
titleEnd = text.length();
}
title = text.substring(0, titleEnd);
if (titleEnd + 1 < text.length()) {
note = text.substring(titleEnd + 1, text.length());
}
else {
note = "";
}
}
/**
* Returns a text where first line is title, rest is note
*/
public String getText() {
String result = "";
if (title != null) {
result += title;
}
if (note != null && !note.isEmpty()) {
// If title is empty, it should remain so
result += "\n" + note;
}
return result;
}
public Task(final Cursor c) {
this._id = c.getLong(0);
this.title = c.getString(1);
note = c.getString(2);
// msec times which can be null
if (!c.isNull(3)) completed = c.getLong(3);
if (!c.isNull(4)) due = c.getLong(4);
if (!c.isNull(5)) updated = c.getLong(5);
// enforced not to be null
left = c.getLong(6);
right = c.getLong(7);
dblist = c.getLong(8);
locked = c.getInt(9) == 1;
}
public Task(final long id, final ContentValues values) {
this(values);
this._id = id;
}
public Task(final Uri uri, final ContentValues values) {
this(Long.parseLong(uri.getLastPathSegment()), values);
}
public Task(final ContentValues values) {
if (values != null) {
if (values.containsKey(TARGETPOS)) {
// Content form getMoveValues
this.left = values.getAsLong(Columns.LEFT);
this.right = values.getAsLong(Columns.RIGHT);
this.dblist = values.getAsLong(Columns.DBLIST);
}
else {
this.title = values.getAsString(Columns.TITLE);
this.note = values.getAsString(Columns.NOTE);
this.completed = values.getAsLong(Columns.COMPLETED);
this.due = values.getAsLong(Columns.DUE);
this.updated = values.getAsLong(Columns.UPDATED);
this.locked = values.getAsLong(Columns.LOCKED) == 1;
this.dblist = values.getAsLong(Columns.DBLIST);
this.left = values.getAsLong(Columns.LEFT);
this.right = values.getAsLong(Columns.RIGHT);
}
}
}
public Task(final JSONObject json) throws JSONException {
if (json.has(Columns.TITLE))
this.title = json.getString(Columns.TITLE);
if (json.has(Columns.NOTE))
this.note = json.getString(Columns.NOTE);
if (json.has(Columns.COMPLETED))
this.completed = json.getLong(Columns.COMPLETED);
if (json.has(Columns.DUE))
this.due = json.getLong(Columns.DUE);
if (json.has(Columns.UPDATED))
this.updated = json.getLong(Columns.UPDATED);
if (json.has(Columns.LOCKED))
this.locked = json.getLong(Columns.LOCKED) == 1;
if (json.has(Columns.DBLIST))
this.dblist = json.getLong(Columns.DBLIST);
if (json.has(Columns.LEFT))
this.left = json.getLong(Columns.LEFT);
if (json.has(Columns.RIGHT))
this.right = json.getLong(Columns.RIGHT);
}
/**
* A move operation should be performed alone. No other information should
* accompany such an update.
*/
public ContentValues getMoveValues(final long targetPos) {
final ContentValues values = new ContentValues();
values.put(TARGETPOS, targetPos);
values.put(Columns.LEFT, left);
values.put(Columns.RIGHT, right);
values.put(Columns.DBLIST, dblist);
return values;
}
/**
* Use this for regular updates of the task.
*/
@Override
public ContentValues getContent() {
final ContentValues values = new ContentValues();
// Note that ID is NOT included here
if (title != null) values.put(Columns.TITLE, title);
if (note != null) values.put(Columns.NOTE, note);
if (dblist != null) values.put(Columns.DBLIST, dblist);
// Never write position values unless you are 110% sure that they are correct
//if (left != null) values.put(Columns.LEFT, left);
//if (right != null) values.put(Columns.RIGHT, right);
values.put(Columns.UPDATED, updated);
values.put(Columns.DUE, due);
values.put(Columns.COMPLETED, completed);
values.put(Columns.LOCKED, locked ? 1 : 0);
return values;
}
/**
* Compares this task to another and returns true if their contents are the
* same. Content is defined as: title, note, duedate, completed != null
* Returns false if title or note are null.
*
* The intended usage is the editor where content and not id's or position
* are of importance.
*/
@Override
public boolean equals(Object o) {
boolean result = false;
if (o instanceof Task) {
final Task other = (Task) o;
result = true;
result &= (title != null && title.equals(other.title));
result &= (note != null && note.equals(other.note));
result &= (due == other.due);
result &= ((completed != null) == (other.completed != null));
}
else {
result = super.equals(o);
}
return result;
}
/**
* Convenience method for normal operations. Updates "updated" field to
* specified Returns number of db-rows affected. Fail if < 1
*/
public int save(final Context context, final long updated) {
int result = 0;
this.updated = updated;
if (_id < 1) {
final Uri uri = context.getContentResolver().insert(getBaseUri(),
getContent());
if (uri != null) {
_id = Long.parseLong(uri.getLastPathSegment());
result++;
}
}
else {
result += context.getContentResolver().update(getUri(),
getContent(), null, null);
}
return result;
}
/**
* Convenience method for normal operations. Updates "updated" field.
* Returns number of db-rows affected. Fail if < 1
*/
@Override
public int save(final Context context) {
return save(context, Calendar.getInstance().getTimeInMillis());
}
/**
* Convenience method to complete tasks in list view for example. Starts an
* asynctask to do the operation in the background.
*/
public static void setCompleted(final Context context,
final boolean completed, final Long... ids) {
if (ids.length > 0) {
final AsyncTask<Long, Void, Void> task = new AsyncTask<Long, Void, Void>() {
@Override
protected Void doInBackground(final Long... ids) {
setCompletedSynced(context, completed, ids);
return null;
}
};
task.execute(ids);
}
}
/**
* Convenience method to complete tasks. Runs on the thread that called it.
* @param context
* @param completed
* @param ids
*/
public static void setCompletedSynced(final Context context,
final boolean completed, final Long... ids) {
if (ids.length < 1) {
return;
}
final ContentValues values = new ContentValues();
values.put(Columns.COMPLETED, completed ? Calendar
.getInstance().getTimeInMillis() : null);
values.put(Columns.UPDATED, Calendar.getInstance()
.getTimeInMillis());
String idStrings = "(";
for (Long id : ids) {
idStrings += id + ",";
}
idStrings = idStrings.substring(0, idStrings.length() - 1);
idStrings += ")";
context.getContentResolver().update(URI, values,
Columns._ID + " IN " + idStrings, null);
}