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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
|
package cgeo.geocaching;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.geopoint.Geopoint;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
public class cgData {
public enum StorageLocation {
HEAP,
CACHE,
DATABASE,
}
/** The list of fields needed for mapping. */
private static final String[] CACHE_COLUMNS = new String[] {
"_id", "updated", "reason", "detailed", "detailedupdate", "visiteddate", "geocode", "cacheid", "guid", "type", "name", "own", "owner", "owner_real", "hidden", "hint", "size",
"difficulty", "distance", "direction", "terrain", "latlon", "location", "latitude", "longitude", "elevation", "shortdesc",
"favourite_cnt", "rating", "votes", "myvote", "disabled", "archived", "members", "found", "favourite", "inventorycoins", "inventorytags",
"inventoryunknown", "onWatchlist", "personal_note", "reliable_latlon", "coordsChanged", "finalDefined"
// reason is replaced by listId in cgCache
};
/** Number of days (as ms) after temporarily saved caches are deleted */
private static long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000;
/**
* holds the column indexes of the cache table to avoid lookups
*/
private static int[] cacheColumnIndex;
private Context context = null;
private CacheCache cacheCache = null;
private String path = null;
private cgDbHelper dbHelper = null;
private SQLiteDatabase databaseRO = null;
private SQLiteDatabase databaseRW = null;
private static final int dbVersion = 62;
private static final int customListIdOffset = 10;
private static final String dbName = "data";
private static final String dbTableCaches = "cg_caches";
private static final String dbTableLists = "cg_lists";
private static final String dbTableAttributes = "cg_attributes";
private static final String dbTableWaypoints = "cg_waypoints";
private static final String dbTableSpoilers = "cg_spoilers";
private static final String dbTableLogs = "cg_logs";
private static final String dbTableLogCount = "cg_logCount";
private static final String dbTableLogImages = "cg_logImages";
private static final String dbTableLogsOffline = "cg_logs_offline";
private static final String dbTableTrackables = "cg_trackables";
private static final String dbTableSearchDestionationHistory = "cg_search_destination_history";
private static final String dbCreateCaches = ""
+ "create table " + dbTableCaches + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, " // cached, favourite...
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "own integer not null default 0, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "latlon text, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "elevation double, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0, "
+ "coordsChanged integer default 0, "
+ "finalDefined integer default 0"
+ "); ";
private static final String dbCreateLists = ""
+ "create table " + dbTableLists + " ("
+ "_id integer primary key autoincrement, "
+ "title text not null, "
+ "updated long not null, "
+ "latitude double, "
+ "longitude double "
+ "); ";
private static final String dbCreateAttributes = ""
+ "create table " + dbTableAttributes + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "attribute text "
+ "); ";
private final static int ATTRIBUTES_GEOCODE = 2;
private final static int ATTRIBUTES_UPDATED = 3;
private final static int ATTRIBUTES_ATTRIBUTE = 4;
private static final String dbCreateWaypoints = ""
+ "create table " + dbTableWaypoints + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latlon text, "
+ "latitude double, "
+ "longitude double, "
+ "note text, "
+ "own integer default 0"
+ "); ";
private static final String dbCreateSpoilers = ""
+ "create table " + dbTableSpoilers + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "url text, "
+ "title text, "
+ "description text "
+ "); ";
private static final String dbCreateLogs = ""
+ "create table " + dbTableLogs + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "author text, "
+ "log text, "
+ "date long, "
+ "found integer not null default 0, "
+ "friend integer "
+ "); ";
private final static int LOGS_GEOCODE = 2;
private final static int LOGS_UPDATED = 3;
private final static int LOGS_TYPE = 4;
private final static int LOGS_AUTHOR = 5;
private final static int LOGS_LOG = 6;
private final static int LOGS_DATE = 7;
private final static int LOGS_FOUND = 8;
private final static int LOGS_FRIEND = 9;
private static final String dbCreateLogCount = ""
+ "create table " + dbTableLogCount + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "count integer not null default 0 "
+ "); ";
private static final String dbCreateLogImages = ""
+ "create table " + dbTableLogImages + " ("
+ "_id integer primary key autoincrement, "
+ "log_id integer not null, "
+ "title text not null, "
+ "url text not null"
+ "); ";
private static final String dbCreateLogsOffline = ""
+ "create table " + dbTableLogsOffline + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "log text, "
+ "date long "
+ "); ";
private static final String dbCreateTrackables = ""
+ "create table " + dbTableTrackables + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, " // date of save
+ "tbcode text not null, "
+ "guid text, "
+ "title text, "
+ "owner text, "
+ "released long, "
+ "goal text, "
+ "description text, "
+ "geocode text "
+ "); ";
private static final String dbCreateSearchDestinationHistory = ""
+ "create table " + dbTableSearchDestionationHistory + " ("
+ "_id integer primary key autoincrement, "
+ "date long not null, "
+ "latitude double, "
+ "longitude double "
+ "); ";
private boolean initialized = false;
private HashMap<String, SQLiteStatement> statements = new HashMap<String, SQLiteStatement>();
private static boolean newlyCreatedDatabase = false;
public cgData(Context contextIn) {
context = contextIn;
cacheCache = CacheCache.getInstance();
}
public synchronized void init() {
if (initialized) {
return;
}
if (databaseRW == null || !databaseRW.isOpen()) {
try {
if (dbHelper == null) {
dbHelper = new cgDbHelper(context);
}
databaseRW = dbHelper.getWritableDatabase();
if (databaseRW != null && databaseRW.isOpen()) {
Log.i(Settings.tag, "Connection to RW database established.");
} else {
Log.e(Settings.tag, "Failed to open connection to RW database.");
}
if (databaseRW != null && databaseRW.inTransaction()) {
databaseRW.endTransaction();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.openDb.RW: " + e.toString());
}
}
if (databaseRO == null || !databaseRO.isOpen()) {
try {
if (dbHelper == null) {
dbHelper = new cgDbHelper(context);
}
databaseRO = dbHelper.getReadableDatabase();
if (databaseRO.needUpgrade(dbVersion)) {
databaseRO = null;
}
if (databaseRO != null && databaseRO.isOpen()) {
Log.i(Settings.tag, "Connection to RO database established.");
} else {
Log.e(Settings.tag, "Failed to open connection to RO database.");
}
if (databaseRO != null && databaseRO.inTransaction()) {
databaseRO.endTransaction();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.openDb.RO: " + e.toString());
}
}
initialized = true;
}
public void closeDb() {
cacheCache.removeAllFromCache();
initialized = false;
closePreparedStatements();
if (databaseRO != null) {
path = databaseRO.getPath();
if (databaseRO.inTransaction()) {
databaseRO.endTransaction();
}
databaseRO.close();
databaseRO = null;
SQLiteDatabase.releaseMemory();
Log.d(Settings.tag, "Closing RO database");
}
if (databaseRW != null) {
path = databaseRW.getPath();
if (databaseRW.inTransaction()) {
databaseRW.endTransaction();
}
databaseRW.close();
databaseRW = null;
SQLiteDatabase.releaseMemory();
Log.d(Settings.tag, "Closing RW database");
}
if (dbHelper != null) {
dbHelper.close();
dbHelper = null;
}
}
private void closePreparedStatements() {
for (SQLiteStatement statement : statements.values()) {
statement.close();
}
}
private static File backupFile() {
return new File(LocalStorage.getStorage(), "cgeo.sqlite");
}
public String backupDatabase() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w(Settings.tag, "Database wasn't backed up: no external memory");
return null;
}
final File target = backupFile();
closeDb();
final boolean backupDone = LocalStorage.copy(new File(path), target);
init();
if (backupDone) {
Log.i(Settings.tag, "Database was copied to " + target);
return target.getPath();
} else {
Log.e(Settings.tag, "Database could not be copied to " + target);
return null;
}
}
public static File isRestoreFile() {
final File fileSourceFile = backupFile();
if (fileSourceFile.exists()) {
return fileSourceFile;
} else {
return null;
}
}
public boolean restoreDatabase() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w(Settings.tag, "Database wasn't restored: no external memory");
return false;
}
final File sourceFile = backupFile();
closeDb();
final boolean restoreDone = LocalStorage.copy(sourceFile, new File(path));
init();
if (restoreDone) {
Log.i(Settings.tag, "Database succesfully restored from " + sourceFile.getPath());
} else {
Log.e(Settings.tag, "Could not restore database from " + sourceFile.getPath());
}
return restoreDone;
}
private static class cgDbHelper extends SQLiteOpenHelper {
cgDbHelper(Context context) {
super(context, dbName, null, dbVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
newlyCreatedDatabase = true;
db.execSQL(dbCreateCaches);
db.execSQL(dbCreateLists);
db.execSQL(dbCreateAttributes);
db.execSQL(dbCreateWaypoints);
db.execSQL(dbCreateSpoilers);
db.execSQL(dbCreateLogs);
db.execSQL(dbCreateLogCount);
db.execSQL(dbCreateLogImages);
db.execSQL(dbCreateLogsOffline);
db.execSQL(dbCreateTrackables);
db.execSQL(dbCreateSearchDestinationHistory);
createIndices(db);
}
static private void createIndices(final SQLiteDatabase db) {
db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)");
db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)");
db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)");
db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)");
db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)");
db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)");
db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)");
db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)");
db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)");
db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)");
db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)");
db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)");
db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)");
db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(Settings.tag, "Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start");
try {
if (db.isReadOnly()) {
return;
}
db.beginTransaction();
if (oldVersion <= 0) { // new table
dropDatabase(db);
onCreate(db);
Log.i(Settings.tag, "Database structure created.");
}
if (oldVersion > 0) {
db.execSQL("delete from " + dbTableCaches + " where reason = 0");
if (oldVersion < 34) { // upgrade to 34
try {
db.execSQL("create index if not exists in_a on " + dbTableCaches + " (geocode)");
db.execSQL("create index if not exists in_b on " + dbTableCaches + " (guid)");
db.execSQL("create index if not exists in_c on " + dbTableCaches + " (reason)");
db.execSQL("create index if not exists in_d on " + dbTableCaches + " (detailed)");
db.execSQL("create index if not exists in_e on " + dbTableCaches + " (type)");
db.execSQL("create index if not exists in_a on " + dbTableAttributes + " (geocode)");
db.execSQL("create index if not exists in_a on " + dbTableWaypoints + " (geocode)");
db.execSQL("create index if not exists in_b on " + dbTableWaypoints + " (geocode, type)");
db.execSQL("create index if not exists in_a on " + dbTableSpoilers + " (geocode)");
db.execSQL("create index if not exists in_a on " + dbTableLogs + " (geocode)");
db.execSQL("create index if not exists in_a on " + dbTableTrackables + " (geocode)");
Log.i(Settings.tag, "Indexes added.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 34: " + e.toString());
}
}
if (oldVersion < 37) { // upgrade to 37
try {
db.execSQL("alter table " + dbTableCaches + " add column direction text");
db.execSQL("alter table " + dbTableCaches + " add column distance double");
Log.i(Settings.tag, "Columns direction and distance added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 37: " + e.toString());
}
}
if (oldVersion < 38) { // upgrade to 38
try {
db.execSQL("drop table " + dbTableLogs);
db.execSQL(dbCreateLogs);
Log.i(Settings.tag, "Changed type column in " + dbTableLogs + " to integer.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 38: " + e.toString());
}
}
if (oldVersion < 39) { // upgrade to 39
try {
db.execSQL(dbCreateLists);
Log.i(Settings.tag, "Created lists table.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 39: " + e.toString());
}
}
if (oldVersion < 40) { // upgrade to 40
try {
db.execSQL("drop table " + dbTableTrackables);
db.execSQL(dbCreateTrackables);
Log.i(Settings.tag, "Changed type of geocode column in trackables table.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 40: " + e.toString());
}
}
if (oldVersion < 41) { // upgrade to 41
try {
db.execSQL("alter table " + dbTableCaches + " add column rating float");
db.execSQL("alter table " + dbTableCaches + " add column votes integer");
db.execSQL("alter table " + dbTableCaches + " add column vote integer");
Log.i(Settings.tag, "Added columns for GCvote.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 41: " + e.toString());
}
}
if (oldVersion < 42) { // upgrade to 42
try {
db.execSQL(dbCreateLogsOffline);
Log.i(Settings.tag, "Added table for offline logs");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 42: " + e.toString());
}
}
if (oldVersion < 43) { // upgrade to 43
try {
final String dbTableCachesTemp = dbTableCaches + "_temp";
final String dbCreateCachesTemp = ""
+ "create temporary table " + dbTableCachesTemp + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, " // cached, favourite...
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "owner text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "latlon text, "
+ "latitude_string text, "
+ "longitude_string text, "
+ "location text, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "shortdesc text, "
+ "description text, "
+ "rating float, "
+ "votes integer, "
+ "vote integer, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0 "
+ "); ";
final String dbCreateCachesNew = ""
+ "create table " + dbTableCaches + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, " // cached, favourite...
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "owner text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "latlon text, "
+ "latitude_string text, "
+ "longitude_string text, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "shortdesc text, "
+ "description text, "
+ "rating float, "
+ "votes integer, "
+ "vote integer, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0 "
+ "); ";
db.beginTransaction();
db.execSQL(dbCreateCachesTemp);
db.execSQL("insert into " + dbTableCachesTemp + " select _id, updated, detailed, detailedupdate, geocode, reason, cacheid, guid, type, name, owner, hidden, hint, size, difficulty, terrain, latlon, latitude_string, longitude_string, location, distance, latitude, longitude, shortdesc, description, rating, votes, vote, disabled, archived, members, found, favourite, inventorycoins, inventorytags, inventoryunknown from " + dbTableCaches);
db.execSQL("drop table " + dbTableCaches);
db.execSQL(dbCreateCachesNew);
db.execSQL("insert into " + dbTableCaches + " select _id, updated, detailed, detailedupdate, geocode, reason, cacheid, guid, type, name, owner, hidden, hint, size, difficulty, terrain, latlon, latitude_string, longitude_string, location, null, distance, latitude, longitude, shortdesc, description, rating, votes, vote, disabled, archived, members, found, favourite, inventorycoins, inventorytags, inventoryunknown from " + dbTableCachesTemp);
db.execSQL("drop table " + dbTableCachesTemp);
db.setTransactionSuccessful();
Log.i(Settings.tag, "Changed direction column");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 43: " + e.toString());
} finally {
db.endTransaction();
}
}
if (oldVersion < 44) { // upgrade to 44
try {
db.execSQL("alter table " + dbTableCaches + " add column favourite_cnt integer");
Log.i(Settings.tag, "Column favourite_cnt added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 44: " + e.toString());
}
}
if (oldVersion < 45) { // upgrade to 45
try {
db.execSQL("alter table " + dbTableCaches + " add column owner_real text");
Log.i(Settings.tag, "Column owner_real added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 45: " + e.toString());
}
}
if (oldVersion < 46) { // upgrade to 46
try {
db.execSQL("alter table " + dbTableCaches + " add column visiteddate long");
db.execSQL("create index if not exists in_f on " + dbTableCaches + " (visiteddate, detailedupdate)");
Log.i(Settings.tag, "Added column for date of visit.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 46: " + e.toString());
}
}
if (oldVersion < 47) { // upgrade to 47
try {
db.execSQL("alter table " + dbTableCaches + " add column own integer not null default 0");
Log.i(Settings.tag, "Added column own.");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 47: " + e.toString());
}
}
if (oldVersion < 48) { // upgrade to 48
try {
db.execSQL("alter table " + dbTableCaches + " add column elevation double");
Log.i(Settings.tag, "Column elevation added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 48: " + e.toString());
}
}
if (oldVersion < 49) { // upgrade to 49
try {
db.execSQL(dbCreateLogCount);
Log.i(Settings.tag, "Created table " + dbTableLogCount + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 49: " + e.toString());
}
}
if (oldVersion < 50) { // upgrade to 50
try {
db.execSQL("alter table " + dbTableCaches + " add column myvote float");
Log.i(Settings.tag, "Added float column for votes to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 50: " + e.toString());
}
}
if (oldVersion < 51) { // upgrade to 51
try {
db.execSQL("alter table " + dbTableCaches + " add column reliable_latlon integer");
Log.i(Settings.tag, "Column reliable_latlon added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 51: " + e.toString());
}
}
if (oldVersion < 52) { // upgrade to 52
try {
db.execSQL(dbCreateSearchDestinationHistory);
Log.i(Settings.tag, "Added table " + dbTableSearchDestionationHistory + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 52", e);
}
}
if (oldVersion < 53) { // upgrade to 53
try {
db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer");
Log.i(Settings.tag, "Column onWatchlist added to " + dbTableCaches + ".");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 53", e);
}
}
if (oldVersion < 54) { // update to 54
try {
db.execSQL(dbCreateLogImages);
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 54: " + e.toString());
}
}
if (oldVersion < 55) { // update to 55
try {
db.execSQL("alter table " + dbTableCaches + " add column personal_note text");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 55: " + e.toString());
}
}
// make all internal attribute names lowercase
// @see issue #299
if (oldVersion < 56) { // update to 56
try {
db.execSQL("update " + dbTableAttributes + " set attribute = " +
"lower(attribute) where attribute like \"%_yes\" " +
"or attribute like \"%_no\"");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 56: " + e.toString());
}
}
// Create missing indices. See issue #435
if (oldVersion < 57) { // update to 57
try {
db.execSQL("drop index in_a");
db.execSQL("drop index in_b");
db.execSQL("drop index in_c");
db.execSQL("drop index in_d");
db.execSQL("drop index in_e");
db.execSQL("drop index in_f");
createIndices(db);
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 57: " + e.toString());
}
}
if (oldVersion < 58) { // upgrade to 58
try {
db.beginTransaction();
final String dbTableCachesTemp = dbTableCaches + "_temp";
final String dbCreateCachesTemp = ""
+ "create table " + dbTableCachesTemp + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, "
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "own integer not null default 0, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "latlon text, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "elevation double, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0 "
+ "); ";
db.execSQL(dbCreateCachesTemp);
db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," +
"hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude,reliable_latlon,elevation," +
"personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," +
"inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches);
db.execSQL("drop table " + dbTableCaches);
db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches);
final String dbTableWaypointsTemp = dbTableWaypoints + "_temp";
final String dbCreateWaypointsTemp = ""
+ "create table " + dbTableWaypointsTemp + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latlon text, "
+ "latitude double, "
+ "longitude double, "
+ "note text "
+ "); ";
db.execSQL(dbCreateWaypointsTemp);
db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latlon, latitude, longitude, note from " + dbTableWaypoints);
db.execSQL("drop table " + dbTableWaypoints);
db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints);
createIndices(db);
db.setTransactionSuccessful();
Log.i(Settings.tag, "Removed latitude_string and longitude_string columns");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 58", e);
} finally {
db.endTransaction();
}
}
if (oldVersion < 59) {
try {
// Add new indices and remove obsolete cache files
createIndices(db);
removeObsoleteCacheDirectories(db);
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 59", e);
}
}
if (oldVersion < 60) {
try {
removeSecEmptyDirs();
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 60", e);
}
}
if (oldVersion < 61) {
try {
db.execSQL("alter table " + dbTableLogs + " add column friend integer");
db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 61: " + e.toString());
}
}
// Introduces finalDefined on caches and own on waypoints
if (oldVersion < 62) {
try {
db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0");
db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0");
db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'");
} catch (Exception e) {
Log.e(Settings.tag, "Failed to upgrade to ver. 62: " + e.toString());
}
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Log.i(Settings.tag, "Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed");
}
}
/**
* Remove obsolete cache directories in c:geo private storage.
*
* @param db
* the read-write database to use
*/
private static void removeObsoleteCacheDirectories(final SQLiteDatabase db) {
final Pattern oldFilePattern = Pattern.compile("^[GC|TB|O][A-Z0-9]{4,7}$");
final SQLiteStatement select = db.compileStatement("select count(*) from " + dbTableCaches + " where geocode = ?");
final File[] files = LocalStorage.getStorage().listFiles();
final ArrayList<File> toRemove = new ArrayList<File>(files.length);
for (final File file : files) {
if (file.isDirectory()) {
final String geocode = file.getName();
if (oldFilePattern.matcher(geocode).find()) {
select.bindString(1, geocode);
if (select.simpleQueryForLong() == 0) {
toRemove.add(file);
}
}
}
}
// Use a background thread for the real removal to avoid keeping the database locked
// if we are called from within a transaction.
new Thread(new Runnable() {
@Override
public void run() {
for (final File dir : toRemove) {
Log.i(Settings.tag, "Removing obsolete cache directory for " + dir.getName());
cgBase.deleteDirectory(dir);
}
}
}).start();
}
/*
* Remove empty directories created in the secondary storage area.
*/
private static void removeSecEmptyDirs() {
for (final File file : LocalStorage.getStorageSec().listFiles()) {
if (file.isDirectory()) {
// This will silently fail if the directory is not empty.
file.delete();
}
}
}
private static void dropDatabase(SQLiteDatabase db) {
db.execSQL("drop table if exists " + dbTableCaches);
db.execSQL("drop table if exists " + dbTableAttributes);
db.execSQL("drop table if exists " + dbTableWaypoints);
db.execSQL("drop table if exists " + dbTableSpoilers);
db.execSQL("drop table if exists " + dbTableLogs);
db.execSQL("drop table if exists " + dbTableLogCount);
db.execSQL("drop table if exists " + dbTableLogsOffline);
db.execSQL("drop table if exists " + dbTableTrackables);
}
public String[] allDetailedThere() {
init();
Cursor cursor = null;
List<String> list = new ArrayList<String>();
try {
long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED;
cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
"(detailed = 1 and detailedupdate > ?) or reason > 0",
new String[] { Long.toString(timestamp) },
null,
null,
"detailedupdate desc",
"100");
if (cursor != null) {
int index = 0;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
index = cursor.getColumnIndex("geocode");
do {
list.add(cursor.getString(index));
} while (cursor.moveToNext());
} else {
cursor.close();
return null;
}
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.allDetailedThere: " + e.toString());
}
if (cursor != null) {
cursor.close();
}
return list.toArray(new String[list.size()]);
}
public boolean isThere(String geocode, String guid, boolean detailed, boolean checkTime) {
init();
Cursor cursor = null;
int cnt = 0;
long dataUpdated = 0;
long dataDetailedUpdate = 0;
int dataDetailed = 0;
try {
if (StringUtils.isNotBlank(geocode)) {
cursor = databaseRO.query(
dbTableCaches,
new String[] { "detailed", "detailedupdate", "updated" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"1");
} else if (StringUtils.isNotBlank(guid)) {
cursor = databaseRO.query(
dbTableCaches,
new String[] { "detailed", "detailedupdate", "updated" },
"guid = ?",
new String[] { guid },
null,
null,
null,
"1");
} else {
return false;
}
if (cursor != null) {
int index = 0;
cnt = cursor.getCount();
if (cnt > 0) {
cursor.moveToFirst();
index = cursor.getColumnIndex("updated");
dataUpdated = cursor.getLong(index);
index = cursor.getColumnIndex("detailedupdate");
dataDetailedUpdate = cursor.getLong(index);
index = cursor.getColumnIndex("detailed");
dataDetailed = cursor.getInt(index);
}
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.isThere: " + e.toString());
}
if (cursor != null) {
cursor.close();
}
if (cnt > 0) {
if (detailed && dataDetailed == 0) {
// we want details, but these are not stored
return false;
}
if (checkTime && detailed && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) {
// we want to check time for detailed cache, but data are older than 3 hours
return false;
}
if (checkTime && !detailed && dataUpdated < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) {
// we want to check time for short cache, but data are older than 3 hours
return false;
}
// we have some cache
return true;
}
// we have no such cache stored in cache
return false;
}
/** Cache stored in DB with listId >= 1 */
// TODO Simply like getCacheDescription()
public boolean isOffline(String geocode, String guid) {
init();
Cursor cursor = null;
long listId = StoredList.TEMPORARY_LIST_ID;
try {
if (StringUtils.isNotBlank(geocode)) {
cursor = databaseRO.query(
dbTableCaches,
new String[] { "reason" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"1");
} else if (StringUtils.isNotBlank(guid)) {
cursor = databaseRO.query(
dbTableCaches,
new String[] { "reason" },
"guid = ? ",
new String[] { guid },
null,
null,
null,
"1");
} else {
return false;
}
if (cursor != null) {
final int cnt = cursor.getCount();
int index = 0;
if (cnt > 0) {
cursor.moveToFirst();
index = cursor.getColumnIndex("reason");
listId = cursor.getLong(index);
}
cursor.close();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.isOffline: " + e.toString());
}
return listId >= StoredList.STANDARD_LIST_ID;
}
public String getGeocodeForGuid(String guid) {
if (StringUtils.isBlank(guid)) {
return null;
}
init();
try {
final SQLiteStatement description = getStatementGeocode();
synchronized (description) {
description.bindString(1, guid);
return description.simpleQueryForString();
}
} catch (SQLiteDoneException e) {
// Do nothing, it only means we have no information on the cache
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getGeocodeForGuid", e);
}
return null;
}
public String getCacheidForGeocode(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
try {
final SQLiteStatement description = getStatementCacheId();
synchronized (description) {
description.bindString(1, geocode);
return description.simpleQueryForString();
}
} catch (SQLiteDoneException e) {
// Do nothing, it only means we have no information on the cache
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getCacheidForGeocode", e);
}
return null;
}
/**
* Save/store a cache to the CacheCache
*
* @param cache
* the Cache to save in the CacheCache/DB
* @param saveFlag
*
* @return true = cache saved successfully to the CacheCache/DB
*/
public boolean saveCache(cgCache cache, EnumSet<LoadFlags.SaveFlag> saveFlags) {
if (cache == null) {
throw new IllegalArgumentException("cache must not be null");
}
// merge always with data already stored in the CacheCache or DB
if (saveFlags.contains(SaveFlag.SAVE_CACHE)) {
cache.gatherMissingFrom(cacheCache.getCacheFromCache(cache.getGeocode()));
cacheCache.putCacheInCache(cache);
}
if (!saveFlags.contains(SaveFlag.SAVE_DB)) {
return true;
}
boolean updateRequired = !cache.gatherMissingFrom(loadCache(cache.getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY));
// only save a cache to the database if
// - the cache is detailed
// - there are changes
// - the cache is only stored in the CacheCache so far
if ((!updateRequired || !cache.isDetailed()) && cache.getStorageLocation().contains(StorageLocation.DATABASE)) {
return false;
}
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
Log.d(Settings.tag, "Saving " + cache.toString() + " (" + cache.getListId() + ") to DB");
ContentValues values = new ContentValues();
if (cache.getUpdated() == 0) {
values.put("updated", System.currentTimeMillis());
} else {
values.put("updated", cache.getUpdated());
}
values.put("reason", cache.getListId());
values.put("detailed", cache.isDetailed() ? 1 : 0);
values.put("detailedupdate", cache.getDetailedUpdate());
values.put("visiteddate", cache.getVisitedDate());
values.put("geocode", cache.getGeocode());
values.put("cacheid", cache.getCacheId());
values.put("guid", cache.getGuid());
values.put("type", cache.getType().id);
values.put("name", cache.getName());
values.put("own", cache.isOwn() ? 1 : 0);
values.put("owner", cache.getOwner());
values.put("owner_real", cache.getOwnerReal());
if (cache.getHiddenDate() == null) {
values.put("hidden", 0);
} else {
values.put("hidden", cache.getHiddenDate().getTime());
}
values.put("hint", cache.getHint());
values.put("size", cache.getSize() == null ? "" : cache.getSize().id);
values.put("difficulty", cache.getDifficulty());
values.put("terrain", cache.getTerrain());
values.put("latlon", cache.getLatlon());
values.put("location", cache.getLocation());
values.put("distance", cache.getDistance());
values.put("direction", cache.getDirection());
putCoords(values, cache.getCoords());
values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0);
values.put("elevation", cache.getElevation());
values.put("shortdesc", cache.getShortdesc());
values.put("personal_note", cache.getPersonalNote());
values.put("description", cache.getDescription());
values.put("favourite_cnt", cache.getFavoritePoints());
values.put("rating", cache.getRating());
values.put("votes", cache.getVotes());
values.put("myvote", cache.getMyVote());
values.put("disabled", cache.isDisabled() ? 1 : 0);
values.put("archived", cache.isArchived() ? 1 : 0);
values.put("members", cache.isPremiumMembersOnly() ? 1 : 0);
values.put("found", cache.isFound() ? 1 : 0);
values.put("favourite", cache.isFavorite() ? 1 : 0);
values.put("inventoryunknown", cache.getInventoryItems());
values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0);
values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0);
values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0);
boolean statusOk = true;
if (cache.hasAttributes()) {
if (!saveAttributes(cache.getGeocode(), cache.getAttributes())) {
statusOk = false;
}
}
if (cache.hasWaypoints()) {
if (!saveWaypoints(cache.getGeocode(), cache.getWaypoints(), true)) {
statusOk = false;
}
}
if (cache.getSpoilers() != null) {
if (!saveSpoilers(cache.getGeocode(), cache.getSpoilers())) {
statusOk = false;
}
}
if (CollectionUtils.isNotEmpty(cache.getLogs())) {
if (!saveLogs(cache.getGeocode(), cache.getLogs())) {
statusOk = false;
}
}
if (MapUtils.isNotEmpty(cache.getLogCounts())) {
if (!saveLogCount(cache.getGeocode(), cache.getLogCounts())) {
statusOk = false;
}
}
if (cache.getInventory() != null) {
if (!saveInventory(cache.getGeocode(), cache.getInventory())) {
statusOk = false;
}
}
if (!statusOk) {
cache.setDetailed(false);
cache.setDetailedUpdate(0L);
}
init();
//try to update record else insert fresh..
boolean result = false;
databaseRW.beginTransaction();
try {
int rows = databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() });
if (rows == 0) {
// cache is not in the DB, insert it
/* long id = */databaseRW.insert(dbTableCaches, null, values);
}
databaseRW.setTransactionSuccessful();
result = true;
} catch (Exception e) {
// nothing
} finally {
databaseRW.endTransaction();
}
values = null;
return result;
}
public boolean saveAttributes(String geocode, List<String> attributes) {
if (StringUtils.isBlank(geocode) || attributes == null) {
return false;
}
init();
databaseRW.beginTransaction();
try {
databaseRW.delete(dbTableAttributes, "geocode = ?", new String[] { geocode });
if (!attributes.isEmpty()) {
InsertHelper helper = new InsertHelper(databaseRW, dbTableAttributes);
long timeStamp = System.currentTimeMillis();
for (String attribute : attributes) {
helper.prepareForInsert();
helper.bind(ATTRIBUTES_GEOCODE, geocode);
helper.bind(ATTRIBUTES_UPDATED, timeStamp);
helper.bind(ATTRIBUTES_ATTRIBUTE, attribute);
helper.execute();
}
helper.close();
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return true;
}
/**
* Persists the given <code>destination</code> into the database.
*
* @param destinations
* @return <code>true</code> if the given destination was successfully
* persisted <code>false</code> otherwise.
*/
public boolean saveSearchedDestination(cgDestination destination) {
boolean success = true;
if (destination == null) {
success = false;
} else {
init();
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("date", destination.getDate());
putCoords(values, destination.getCoords());
long id = databaseRW.insert(dbTableSearchDestionationHistory, null, values);
destination.setId(id);
databaseRW.setTransactionSuccessful();
} catch (Exception e) {
success = false;
Log.e(Settings.tag, "Updating searchedDestinations db failed", e);
} finally {
databaseRW.endTransaction();
}
}
return success;
}
public boolean saveWaypoints(String geocode, List<cgWaypoint> waypoints, boolean drop) {
if (StringUtils.isBlank(geocode) || waypoints == null) {
return false;
}
init();
Log.d(Settings.tag, "cgData.saveWaypoints(drop=" + drop + ")");
boolean ok = false;
databaseRW.beginTransaction();
try {
if (drop) {
databaseRW.delete(dbTableWaypoints, "geocode = ? and type <> ? and own = 0", new String[] { geocode, "own" });
}
if (!waypoints.isEmpty()) {
ContentValues values = new ContentValues();
long timeStamp = System.currentTimeMillis();
for (cgWaypoint oneWaypoint : waypoints) {
if (oneWaypoint.isUserDefined()) {
continue;
}
values.clear();
values.put("geocode", geocode);
values.put("updated", timeStamp);
values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null);
values.put("prefix", oneWaypoint.getPrefix());
values.put("lookup", oneWaypoint.getLookup());
values.put("name", oneWaypoint.getName());
values.put("latlon", oneWaypoint.getLatlon());
putCoords(values, oneWaypoint.getCoords());
values.put("note", oneWaypoint.getNote());
values.put("own", oneWaypoint.isUserDefined() ? 1 : 0);
final long rowId = databaseRW.insert(dbTableWaypoints, null, values);
oneWaypoint.setId((int) rowId);
}
}
databaseRW.setTransactionSuccessful();
ok = true;
} finally {
databaseRW.endTransaction();
}
return ok;
}
/**
* Save coordinates into a ContentValues
*
* @param values
* a ContentValues to save coordinates in
* @param oneWaypoint
* coordinates to save, or null to save empty coordinates
*/
private static void putCoords(final ContentValues values, final Geopoint coords) {
values.put("latitude", coords == null ? null : coords.getLatitude());
values.put("longitude", coords == null ? null : coords.getLongitude());
}
/**
* Retrieve coordinates from a Cursor
*
* @param cursor
* a Cursor representing a row in the database
* @param indexLat
* index of the latitude column
* @param indexLon
* index of the longitude column
* @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid
*/
private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) {
if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) {
return null;
}
return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon));
}
public boolean saveOwnWaypoint(int id, String geocode, cgWaypoint waypoint) {
if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) {
return false;
}
init();
boolean ok = false;
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null);
values.put("prefix", waypoint.getPrefix());
values.put("lookup", waypoint.getLookup());
values.put("name", waypoint.getName());
values.put("latlon", waypoint.getLatlon());
putCoords(values, waypoint.getCoords());
values.put("note", waypoint.getNote());
values.put("own", waypoint.isUserDefined() ? 1 : 0);
if (id <= 0) {
final long rowId = databaseRW.insert(dbTableWaypoints, null, values);
waypoint.setId((int) rowId);
ok = true;
} else {
final int rows = databaseRW.update(dbTableWaypoints, values, "_id = " + id, null);
if (rows > 0) {
ok = true;
} else {
ok = false;
}
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return ok;
}
public boolean deleteWaypoint(int id) {
if (id == 0) {
return false;
}
init();
int deleted = databaseRW.delete(dbTableWaypoints, "_id = " + id, null);
if (deleted > 0) {
return true;
}
return false;
}
public boolean saveSpoilers(String geocode, List<cgImage> spoilers) {
if (StringUtils.isBlank(geocode) || spoilers == null) {
return false;
}
init();
databaseRW.beginTransaction();
try {
databaseRW.delete(dbTableSpoilers, "geocode = ?", new String[] { geocode });
if (!spoilers.isEmpty()) {
ContentValues values = new ContentValues();
long timeStamp = System.currentTimeMillis();
for (cgImage oneSpoiler : spoilers) {
values.clear();
values.put("geocode", geocode);
values.put("updated", timeStamp);
values.put("url", oneSpoiler.getUrl());
values.put("title", oneSpoiler.getTitle());
values.put("description", oneSpoiler.getDescription());
databaseRW.insert(dbTableSpoilers, null, values);
}
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return true;
}
public boolean saveLogs(String geocode, List<cgLog> logs) {
return saveLogs(geocode, logs, true);
}
public boolean saveLogs(String geocode, List<cgLog> logs, boolean drop) {
if (StringUtils.isBlank(geocode) || logs == null) {
return false;
}
init();
databaseRW.beginTransaction();
try {
if (drop) {
// TODO delete logimages referring these logs
databaseRW.delete(dbTableLogs, "geocode = ?", new String[] { geocode });
}
if (!logs.isEmpty()) {
InsertHelper helper = new InsertHelper(databaseRW, dbTableLogs);
long timeStamp = System.currentTimeMillis();
for (cgLog log : logs) {
helper.prepareForInsert();
helper.bind(LOGS_GEOCODE, geocode);
helper.bind(LOGS_UPDATED, timeStamp);
helper.bind(LOGS_TYPE, log.type.id);
helper.bind(LOGS_AUTHOR, log.author);
helper.bind(LOGS_LOG, log.log);
helper.bind(LOGS_DATE, log.date);
helper.bind(LOGS_FOUND, log.found);
helper.bind(LOGS_FRIEND, log.friend);
long log_id = helper.execute();
if (CollectionUtils.isNotEmpty(log.logImages)) {
ContentValues values = new ContentValues();
for (cgImage img : log.logImages) {
values.clear();
values.put("log_id", log_id);
values.put("title", img.getTitle());
values.put("url", img.getUrl());
databaseRW.insert(dbTableLogImages, null, values);
}
}
}
helper.close();
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return true;
}
public boolean saveLogCount(String geocode, Map<LogType, Integer> logCounts) {
return saveLogCount(geocode, logCounts, true);
}
public boolean saveLogCount(String geocode, Map<LogType, Integer> logCounts, boolean drop) {
if (StringUtils.isBlank(geocode) || MapUtils.isEmpty(logCounts)) {
return false;
}
init();
databaseRW.beginTransaction();
try {
if (drop) {
databaseRW.delete(dbTableLogCount, "geocode = ?", new String[] { geocode });
}
ContentValues values = new ContentValues();
Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet();
long timeStamp = System.currentTimeMillis();
for (Entry<LogType, Integer> pair : logCountsItems) {
values.clear();
values.put("geocode", geocode);
values.put("updated", timeStamp);
values.put("type", pair.getKey().id);
values.put("count", pair.getValue());
databaseRW.insert(dbTableLogCount, null, values);
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return true;
}
public boolean saveInventory(String geocode, List<cgTrackable> trackables) {
if (trackables == null) {
return false;
}
init();
databaseRW.beginTransaction();
try {
if (geocode != null) {
databaseRW.delete(dbTableTrackables, "geocode = ?", new String[] { geocode });
}
if (!trackables.isEmpty()) {
ContentValues values = new ContentValues();
long timeStamp = System.currentTimeMillis();
for (cgTrackable oneTrackable : trackables) {
values.clear();
if (geocode != null) {
values.put("geocode", geocode);
}
values.put("updated", timeStamp);
values.put("tbcode", oneTrackable.getGeocode());
values.put("guid", oneTrackable.getGuid());
values.put("title", oneTrackable.getName());
values.put("owner", oneTrackable.getOwner());
if (oneTrackable.getReleased() != null) {
values.put("released", oneTrackable.getReleased().getTime());
} else {
values.put("released", 0L);
}
values.put("goal", oneTrackable.getGoal());
values.put("description", oneTrackable.getDetails());
databaseRW.insert(dbTableTrackables, null, values);
saveLogs(oneTrackable.getGeocode(), oneTrackable.getLogs());
}
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return true;
}
public List<Number> getBounds(Set<String> geocodes) {
if (CollectionUtils.isEmpty(geocodes)) {
return null;
}
final Set<cgCache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB);
double latMin = 360.0;
double latMax = -360.0;
double lonMin = 360.0;
double lonMax = -360.0;
for (cgCache cache : caches) {
final Geopoint coords = cache.getCoords();
double latitude = coords.getLatitude();
latMin = Math.min(latitude, latMin);
latMax = Math.max(latitude, latMax);
double longitude = coords.getLongitude();
lonMin = Math.min(longitude, lonMin);
lonMax = Math.max(longitude, lonMax);
}
final List<Number> viewport = new ArrayList<Number>();
viewport.add(caches.size());
viewport.add(latMin);
viewport.add(latMax);
viewport.add(lonMin);
viewport.add(lonMax);
return viewport;
}
/**
* Load a single Cache.
*
* @param geocode
* The Geocode GCXXXX
* @return the loaded cache (if found). Can be null
*/
public cgCache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) {
if (StringUtils.isBlank(geocode)) {
throw new IllegalArgumentException("geocode must not be empty");
}
Set<String> geocodes = new HashSet<String>();
geocodes.add(geocode);
Set<cgCache> caches = loadCaches(geocodes, loadFlags);
if (caches != null && caches.size() >= 1) {
return (cgCache) caches.toArray()[0];
}
return null;
}
/**
* Load caches.
*
* @param geocodes
* @return Set of loaded caches. Never null.
*/
public Set<cgCache> loadCaches(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return new HashSet<cgCache>();
}
Set<cgCache> result = new HashSet<cgCache>();
Set<String> remaining = new HashSet<String>(geocodes);
if (loadFlags.contains(LoadFlag.LOAD_CACHE_BEFORE)) {
for (String geocode : new HashSet<String>(remaining)) {
cgCache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (loadFlags.contains(LoadFlag.LOAD_DB_MINIMAL) ||
loadFlags.contains(LoadFlag.LOAD_ATTRIBUTES) ||
loadFlags.contains(LoadFlag.LOAD_WAYPOINTS) ||
loadFlags.contains(LoadFlag.LOAD_SPOILERS) ||
loadFlags.contains(LoadFlag.LOAD_LOGS) ||
loadFlags.contains(LoadFlag.LOAD_INVENTORY) ||
loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) {
Set<cgCache> cachesFromDB = loadCaches(remaining, null, null, null, null, loadFlags);
if (cachesFromDB != null) {
result.addAll(cachesFromDB);
for (cgCache cache : cachesFromDB) {
remaining.remove(cache.getGeocode());
}
}
}
if (loadFlags.contains(LoadFlag.LOAD_CACHE_AFTER)) {
for (String geocode : new HashSet<String>(remaining)) {
cgCache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (remaining.size() >= 1) {
Log.e(Settings.tag, "cgData.loadCaches(" + remaining.toString() + ") failed");
}
return result;
}
/**
* Load caches.
*
* @param geocodes
* OR
* @param centerLat
* @param centerLon
* @param spanLat
* @param spanLon
* @param loadFlags
* @return Set of loaded caches. Never null.
*/
public Set<cgCache> loadCaches(final Set<String> geocodes, final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final EnumSet<LoadFlag> loadFlags) {
final Set<cgCache> caches = new HashSet<cgCache>();
if (CollectionUtils.isEmpty(geocodes)) {
return caches;
}
// Using more than one of the parametersets results in overly comlex wheres
if (CollectionUtils.isNotEmpty(geocodes)
&& centerLat != null
&& centerLon != null
&& spanLat != null
&& spanLon != null) {
throw new IllegalArgumentException("Please use only one parameter");
}
Log.d(Settings.tag, "cgData.loadCaches(" + geocodes.toString() + ") from DB");
init();
Cursor cursor = null;
try {
StringBuilder where = cgData.whereGeocodeIn(geocodes);
// viewport limitation
if (centerLat != null && centerLon != null && spanLat != null && spanLon != null) {
double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4);
double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4);
double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4);
double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4);
double llCache;
if (latMin > latMax) {
llCache = latMax;
latMax = latMin;
latMin = llCache;
}
if (lonMin > lonMax) {
llCache = lonMax;
lonMax = lonMin;
lonMin = llCache;
}
if (where.length() > 0) {
where.append(" and ");
}
where.append("(latitude >= ");
where.append(String.format((Locale) null, "%.6f", latMin));
where.append(" and latitude <= ");
where.append(String.format((Locale) null, "%.6f", latMax));
where.append(" and longitude >= ");
where.append(String.format((Locale) null, "%.6f", lonMin));
where.append(" and longitude <= ");
where.append(String.format((Locale) null, "%.6f", lonMax));
where.append(')');
}
cursor = databaseRO.query(
dbTableCaches,
CACHE_COLUMNS,
where.toString(),
null,
null,
null,
null,
null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
//Extracted Method = LOADDBMINIMAL
cgCache cache = cgData.createCacheFromDatabaseContent(cursor);
if (loadFlags.contains(LoadFlag.LOAD_ATTRIBUTES)) {
cache.setAttributes(loadAttributes(cache.getGeocode()));
}
if (loadFlags.contains(LoadFlag.LOAD_WAYPOINTS)) {
final List<cgWaypoint> waypoints = loadWaypoints(cache.getGeocode());
if (CollectionUtils.isNotEmpty(waypoints)) {
cache.setWaypoints(waypoints, false);
}
}
if (loadFlags.contains(LoadFlag.LOAD_SPOILERS)) {
final List<cgImage> spoilers = loadSpoilers(cache.getGeocode());
if (CollectionUtils.isNotEmpty(spoilers)) {
if (cache.getSpoilers() == null) {
cache.setSpoilers(new ArrayList<cgImage>());
} else {
cache.getSpoilers().clear();
}
cache.getSpoilers().addAll(spoilers);
}
}
if (loadFlags.contains(LoadFlag.LOAD_LOGS)) {
cache.setLogs(loadLogs(cache.getGeocode()));
final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode());
if (MapUtils.isNotEmpty(logCounts)) {
cache.getLogCounts().clear();
cache.getLogCounts().putAll(logCounts);
}
}
if (loadFlags.contains(LoadFlag.LOAD_INVENTORY)) {
final List<cgTrackable> inventory = loadInventory(cache.getGeocode());
if (CollectionUtils.isNotEmpty(inventory)) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<cgTrackable>());
} else {
cache.getInventory().clear();
}
cache.getInventory().addAll(inventory);
}
}
if (loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) {
cache.setLogOffline(hasLogOffline(cache.getGeocode()));
}
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
caches.add(cache);
} while (cursor.moveToNext());
}
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getCaches: " + e.toString());
}
if (cursor != null) {
cursor.close();
}
return caches;
}
/**
* creates a Cache from the cursor. Doesn't next.
*
* @param cursor
* @return Cache from DB
*/
private static cgCache createCacheFromDatabaseContent(Cursor cursor) {
int index;
cgCache cache = new cgCache();
if (cacheColumnIndex == null) {
int[] local_cci = new int[41]; // use a local variable to avoid having the not yet fully initialized array be visible to other threads
local_cci[0] = cursor.getColumnIndex("updated");
local_cci[1] = cursor.getColumnIndex("reason");
local_cci[2] = cursor.getColumnIndex("detailed");
local_cci[3] = cursor.getColumnIndex("detailedupdate");
local_cci[4] = cursor.getColumnIndex("visiteddate");
local_cci[5] = cursor.getColumnIndex("geocode");
local_cci[6] = cursor.getColumnIndex("cacheid");
local_cci[7] = cursor.getColumnIndex("guid");
local_cci[8] = cursor.getColumnIndex("type");
local_cci[9] = cursor.getColumnIndex("name");
local_cci[10] = cursor.getColumnIndex("own");
local_cci[11] = cursor.getColumnIndex("owner");
local_cci[12] = cursor.getColumnIndex("owner_real");
local_cci[13] = cursor.getColumnIndex("hidden");
local_cci[14] = cursor.getColumnIndex("hint");
local_cci[15] = cursor.getColumnIndex("size");
local_cci[16] = cursor.getColumnIndex("difficulty");
local_cci[17] = cursor.getColumnIndex("direction");
local_cci[18] = cursor.getColumnIndex("distance");
local_cci[19] = cursor.getColumnIndex("terrain");
local_cci[20] = cursor.getColumnIndex("latlon");
local_cci[21] = cursor.getColumnIndex("location");
local_cci[22] = cursor.getColumnIndex("elevation");
local_cci[23] = cursor.getColumnIndex("personal_note");
local_cci[24] = cursor.getColumnIndex("shortdesc");
local_cci[25] = cursor.getColumnIndex("favourite_cnt");
local_cci[26] = cursor.getColumnIndex("rating");
local_cci[27] = cursor.getColumnIndex("votes");
local_cci[28] = cursor.getColumnIndex("myvote");
local_cci[29] = cursor.getColumnIndex("disabled");
local_cci[30] = cursor.getColumnIndex("archived");
local_cci[31] = cursor.getColumnIndex("members");
local_cci[32] = cursor.getColumnIndex("found");
local_cci[33] = cursor.getColumnIndex("favourite");
local_cci[34] = cursor.getColumnIndex("inventoryunknown");
local_cci[35] = cursor.getColumnIndex("onWatchlist");
local_cci[36] = cursor.getColumnIndex("reliable_latlon");
local_cci[37] = cursor.getColumnIndex("coordsChanged");
local_cci[38] = cursor.getColumnIndex("latitude");
local_cci[39] = cursor.getColumnIndex("longitude");
local_cci[40] = cursor.getColumnIndex("finalDefined");
cacheColumnIndex = local_cci;
}
cache.setUpdated(cursor.getLong(cacheColumnIndex[0]));
cache.setListId(cursor.getInt(cacheColumnIndex[1]));
cache.setDetailed(cursor.getInt(cacheColumnIndex[2]) == 1);
cache.setDetailedUpdate(cursor.getLong(cacheColumnIndex[3]));
cache.setVisitedDate(cursor.getLong(cacheColumnIndex[4]));
cache.setGeocode(cursor.getString(cacheColumnIndex[5]));
cache.setCacheId(cursor.getString(cacheColumnIndex[6]));
cache.setGuid(cursor.getString(cacheColumnIndex[7]));
cache.setType(CacheType.getById(cursor.getString(cacheColumnIndex[8])));
cache.setName(cursor.getString(cacheColumnIndex[9]));
cache.setOwn(cursor.getInt(cacheColumnIndex[10]) == 1);
cache.setOwner(cursor.getString(cacheColumnIndex[11]));
cache.setOwnerReal(cursor.getString(cacheColumnIndex[12]));
long dateValue = cursor.getLong(cacheColumnIndex[13]);
if (dateValue != 0) {
cache.setHidden(new Date(dateValue));
}
cache.setHint(cursor.getString(cacheColumnIndex[14]));
cache.setSize(CacheSize.getById(cursor.getString(cacheColumnIndex[15])));
cache.setDifficulty(cursor.getFloat(cacheColumnIndex[16]));
index = cacheColumnIndex[17];
if (cursor.isNull(index)) {
cache.setDirection(null);
} else {
cache.setDirection(cursor.getFloat(index));
}
index = cacheColumnIndex[18];
if (cursor.isNull(index)) {
cache.setDistance(null);
} else {
cache.setDistance(cursor.getFloat(index));
}
cache.setTerrain(cursor.getFloat(cacheColumnIndex[19]));
cache.setLatlon(cursor.getString(cacheColumnIndex[20]));
cache.setLocation(cursor.getString(cacheColumnIndex[21]));
cache.setCoords(getCoords(cursor, cacheColumnIndex[38], cacheColumnIndex[39]));
index = cacheColumnIndex[22];
if (cursor.isNull(index)) {
cache.setElevation(null);
} else {
cache.setElevation(cursor.getDouble(index));
}
cache.setPersonalNote(cursor.getString(cacheColumnIndex[23]));
cache.setShortdesc(cursor.getString(cacheColumnIndex[24]));
// do not set cache.description !
cache.setFavoritePoints(cursor.getInt(cacheColumnIndex[25]));
cache.setRating(cursor.getFloat(cacheColumnIndex[26]));
cache.setVotes(cursor.getInt(cacheColumnIndex[27]));
cache.setMyVote(cursor.getFloat(cacheColumnIndex[28]));
cache.setDisabled(cursor.getInt(cacheColumnIndex[29]) == 1);
cache.setArchived(cursor.getInt(cacheColumnIndex[30]) == 1);
cache.setPremiumMembersOnly(cursor.getInt(cacheColumnIndex[31]) == 1);
cache.setFound(cursor.getInt(cacheColumnIndex[32]) == 1);
cache.setFavorite(cursor.getInt(cacheColumnIndex[33]) == 1);
cache.setInventoryItems(cursor.getInt(cacheColumnIndex[34]));
cache.setOnWatchlist(cursor.getInt(cacheColumnIndex[35]) == 1);
cache.setReliableLatLon(cursor.getInt(cacheColumnIndex[36]) > 0);
cache.setUserModifiedCoords(cursor.getInt(cacheColumnIndex[37]) > 0);
cache.setFinalDefined(cursor.getInt(cacheColumnIndex[40]) > 0);
Log.d(Settings.tag, "Loading " + cache.toString() + " (" + cache.getListId() + ") from DB");
return cache;
}
public List<String> loadAttributes(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
ArrayList<String> attributes = new ArrayList<String>();
Cursor cursor = databaseRO.query(
dbTableAttributes,
new String[] { "attribute" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"100");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int index = cursor.getColumnIndex("attribute");
do {
attributes.add(cursor.getString(index));
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return attributes;
}
public cgWaypoint loadWaypoint(int id) {
if (id == 0) {
return null;
}
init();
cgWaypoint waypoint = null;
Cursor cursor = databaseRO.query(
dbTableWaypoints,
new String[] { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latlon", "latitude", "longitude", "note", "own" },
"_id = ?",
new String[] { Integer.toString(id) },
null,
null,
null,
"1");
Log.d(Settings.tag, "cgData.loadWaypoint(" + id + ")");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
waypoint = createWaypointFromDatabaseContent(cursor);
}
if (cursor != null) {
cursor.close();
}
return waypoint;
}
public List<cgWaypoint> loadWaypoints(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
List<cgWaypoint> waypoints = new ArrayList<cgWaypoint>();
Cursor cursor = databaseRO.query(
dbTableWaypoints,
new String[] { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latlon", "latitude", "longitude", "note", "own" },
"geocode = ?",
new String[] { geocode },
null,
null,
"_id",
"100");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
cgWaypoint waypoint = createWaypointFromDatabaseContent(cursor);
waypoints.add(waypoint);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return waypoints;
}
private static cgWaypoint createWaypointFromDatabaseContent(Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex("name"));
WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type")));
boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0;
cgWaypoint waypoint = new cgWaypoint(name, type, own);
waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id")));
waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode")));
waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix")));
waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup")));
waypoint.setLatlon(cursor.getString(cursor.getColumnIndex("latlon")));
waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude")));
waypoint.setNote(cursor.getString(cursor.getColumnIndex("note")));
return waypoint;
}
public List<cgImage> loadSpoilers(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
List<cgImage> spoilers = new ArrayList<cgImage>();
Cursor cursor = databaseRO.query(
dbTableSpoilers,
new String[] { "url", "title", "description" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"100");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int indexUrl = cursor.getColumnIndex("url");
int indexTitle = cursor.getColumnIndex("title");
int indexDescription = cursor.getColumnIndex("description");
do {
cgImage spoiler = new cgImage(cursor.getString(indexUrl), cursor.getString(indexTitle), cursor.getString(indexDescription));
spoilers.add(spoiler);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return spoilers;
}
/**
* Loads the history of previously entered destinations from
* the database. If no destinations exist, an {@link Collections#emptyList()} will be returned.
*
* @return A list of previously entered destinations or an empty list.
*/
public List<cgDestination> loadHistoryOfSearchedLocations() {
init();
Cursor cursor = databaseRO.query(dbTableSearchDestionationHistory,
new String[] { "_id", "date", "latitude", "longitude" },
null,
null,
null,
null,
"date desc",
"100");
final List<cgDestination> destinations = new LinkedList<cgDestination>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int indexId = cursor.getColumnIndex("_id");
int indexDate = cursor.getColumnIndex("date");
int indexLatitude = cursor.getColumnIndex("latitude");
int indexLongitude = cursor.getColumnIndex("longitude");
do {
final cgDestination dest = new cgDestination();
dest.setId(cursor.getLong(indexId));
dest.setDate(cursor.getLong(indexDate));
dest.setCoords(getCoords(cursor, indexLatitude, indexLongitude));
// If coordinates are non-existent or invalid, do not consider
// this point.
if (dest.getCoords() != null) {
destinations.add(dest);
}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return destinations;
}
public boolean clearSearchedDestinations() {
boolean success = true;
init();
databaseRW.beginTransaction();
try {
databaseRW.delete(dbTableSearchDestionationHistory, null, null);
databaseRW.setTransactionSuccessful();
} catch (Exception e) {
success = false;
Log.e(Settings.tag, "Unable to clear searched destinations", e);
} finally {
databaseRW.endTransaction();
}
return success;
}
public List<cgLog> loadLogs(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
List<cgLog> logs = new ArrayList<cgLog>();
Cursor cursor = databaseRO.rawQuery(
"SELECT cg_logs._id as cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url FROM "
+ dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages
+ " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date desc, cg_logs._id asc", new String[] { geocode });
if (cursor != null && cursor.getCount() > 0) {
cgLog log = null;
int indexLogsId = cursor.getColumnIndex("cg_logs_id");
int indexType = cursor.getColumnIndex("type");
int indexAuthor = cursor.getColumnIndex("author");
int indexLog = cursor.getColumnIndex("log");
int indexDate = cursor.getColumnIndex("date");
int indexFound = cursor.getColumnIndex("found");
int indexFriend = cursor.getColumnIndex("friend");
int indexLogImagesId = cursor.getColumnIndex("cg_logImages_id");
int indexTitle = cursor.getColumnIndex("title");
int indexUrl = cursor.getColumnIndex("url");
while (cursor.moveToNext() && logs.size() < 100) {
if (log == null || log.id != cursor.getInt(indexLogsId)) {
log = new cgLog();
log.id = cursor.getInt(indexLogsId);
log.type = LogType.getById(cursor.getInt(indexType));
log.author = cursor.getString(indexAuthor);
log.log = cursor.getString(indexLog);
log.date = cursor.getLong(indexDate);
log.found = cursor.getInt(indexFound);
log.friend = cursor.getInt(indexFriend) == 1 ? true : false;
logs.add(log);
}
if (!cursor.isNull(indexLogImagesId)) {
String title = cursor.getString(indexTitle);
String url = cursor.getString(indexUrl);
if (log.logImages == null) {
log.logImages = new ArrayList<cgImage>();
}
final cgImage log_img = new cgImage(url, title);
log.logImages.add(log_img);
}
}
}
if (cursor != null) {
cursor.close();
}
return logs;
}
public Map<LogType, Integer> loadLogCounts(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
Map<LogType, Integer> logCounts = new HashMap<LogType, Integer>();
Cursor cursor = databaseRO.query(
dbTableLogCount,
new String[] { "type", "count" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"100");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int indexType = cursor.getColumnIndex("type");
int indexCount = cursor.getColumnIndex("count");
do {
LogType type = LogType.getById(cursor.getInt(indexType));
Integer count = cursor.getInt(indexCount);
logCounts.put(type, count);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return logCounts;
}
public List<cgTrackable> loadInventory(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
List<cgTrackable> trackables = new ArrayList<cgTrackable>();
Cursor cursor = databaseRO.query(
dbTableTrackables,
new String[] { "_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description" },
"geocode = ?",
new String[] { geocode },
null,
null,
"title COLLATE NOCASE ASC",
"100");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
cgTrackable trackable = createTrackableFromDatabaseContent(cursor);
trackables.add(trackable);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return trackables;
}
public cgTrackable loadTrackable(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
cgTrackable trackable = new cgTrackable();
Cursor cursor = databaseRO.query(
dbTableTrackables,
new String[] { "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description" },
"tbcode = ?",
new String[] { geocode },
null,
null,
null,
"1");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
trackable = createTrackableFromDatabaseContent(cursor);
}
if (cursor != null) {
cursor.close();
}
return trackable;
}
private cgTrackable createTrackableFromDatabaseContent(Cursor cursor) {
cgTrackable trackable = new cgTrackable();
trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode")));
trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid")));
trackable.setName(cursor.getString(cursor.getColumnIndex("title")));
trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner")));
String releasedPre = cursor.getString(cursor.getColumnIndex("released"));
if (releasedPre != null && Long.getLong(releasedPre) != null) {
trackable.setReleased(new Date(Long.getLong(releasedPre)));
} else {
trackable.setReleased(null);
}
trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal")));
trackable.setDetails(cursor.getString(cursor.getColumnIndex("description")));
trackable.setLogs(loadLogs(trackable.getGeocode()));
return trackable;
}
/**
* Number of caches stored. The number is shown on the starting activitiy of c:geo
*
* @param detailedOnly
* @param cacheType
* @param list
* @return
*/
public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final Integer list) {
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
init();
String listSql = null;
String listSqlW = null;
if (list == null) {
listSql = " where reason >= 1";
listSqlW = " and reason >= 1";
} else if (list >= 1) {
listSql = " where reason = " + list;
listSqlW = " and reason = " + list;
} else {
return 0;
}
int count = 0;
try {
String sql = "select count(_id) from " + dbTableCaches; // this default is not used, but we like to have variables initialized
if (!detailedOnly) {
if (cacheType == CacheType.ALL) {
sql = "select count(_id) from " + dbTableCaches + listSql;
} else {
sql = "select count(_id) from " + dbTableCaches + " where type = \"" + cacheType.id + "\"" + listSqlW;
}
} else {
if (cacheType == CacheType.ALL) {
sql = "select count(_id) from " + dbTableCaches + " where detailed = 1" + listSqlW;
} else {
sql = "select count(_id) from " + dbTableCaches + " where detailed = 1 and type = \"" + cacheType.id + "\"" + listSqlW;
}
}
SQLiteStatement compiledStmnt = databaseRO.compileStatement(sql);
count = (int) compiledStmnt.simpleQueryForLong();
compiledStmnt.close();
} catch (Exception e) {
Log.e(Settings.tag, "cgData.loadAllStoredCachesCount: " + e.toString());
}
return count;
}
public int getAllHistoricCachesCount() {
init();
int count = 0;
try {
SQLiteStatement sqlCount = databaseRO.compileStatement("select count(_id) from " + dbTableCaches + " where visiteddate > 0");
count = (int) sqlCount.simpleQueryForLong();
sqlCount.close();
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getAllHistoricCachesCount: " + e.toString());
}
return count;
}
public Set<String> loadBatchOfStoredGeocodes(final boolean detailedOnly, final Geopoint coords, final CacheType cacheType, final int listId) {
if (coords == null) {
throw new IllegalArgumentException("coords must not be null");
}
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
init();
Set<String> geocodes = new HashSet<String>();
StringBuilder specifySql = new StringBuilder();
specifySql.append("reason = ");
specifySql.append(Math.max(listId, 1));
if (detailedOnly) {
specifySql.append(" and detailed = 1 ");
}
if (cacheType != CacheType.ALL) {
specifySql.append(" and type = \"");
specifySql.append(cacheType.id);
specifySql.append('"');
}
try {
Cursor cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) +
") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif" },
specifySql.toString(),
null,
null,
null,
"dif",
null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int index = cursor.getColumnIndex("geocode");
do {
geocodes.add(cursor.getString(index));
} while (cursor.moveToNext());
}
cursor.close();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.loadBatchOfStoredGeocodes: " + e.toString());
}
return geocodes;
}
public Set<String> loadBatchOfHistoricGeocodes(final boolean detailedOnly, final CacheType cacheType) {
init();
Set<String> geocodes = new HashSet<String>();
StringBuilder specifySql = new StringBuilder();
specifySql.append("visiteddate > 0");
if (detailedOnly) {
specifySql.append(" and detailed = 1");
}
if (cacheType != CacheType.ALL) {
specifySql.append(" and type = \"");
specifySql.append(cacheType.id);
specifySql.append('"');
}
try {
Cursor cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
specifySql.toString(),
null,
null,
null,
"visiteddate",
null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int index = cursor.getColumnIndex("geocode");
do {
geocodes.add(cursor.getString(index));
} while (cursor.moveToNext());
} else {
cursor.close();
return null;
}
cursor.close();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.loadBatchOfHistoricGeocodes: " + e.toString());
}
return geocodes;
}
/** Retrieve all stored caches from DB */
public Set<String> loadCachedInViewport(final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final CacheType cacheType) {
return loadInViewport(false, centerLat, centerLon, spanLat, spanLon, cacheType);
}
/** Retrieve stored caches from DB with listId >= 1 */
public Set<String> loadStoredInViewport(final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final CacheType cacheType) {
return loadInViewport(true, centerLat, centerLon, spanLat, spanLon, cacheType);
}
public Set<String> loadInViewport(final boolean stored, final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final CacheType cacheType) {
if (centerLat == null || centerLon == null || spanLat == null || spanLon == null) {
return null;
}
init();
Set<String> geocodes = new HashSet<String>();
// viewport limitation
double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4);
double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4);
double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4);
double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4);
double llCache;
if (latMin > latMax) {
llCache = latMax;
latMax = latMin;
latMin = llCache;
}
if (lonMin > lonMax) {
llCache = lonMax;
lonMax = lonMin;
lonMin = llCache;
}
StringBuilder where = new StringBuilder();
where.append("latitude >= ");
where.append(String.format((Locale) null, "%.6f", latMin));
where.append(" and latitude <= ");
where.append(String.format((Locale) null, "%.6f", latMax));
where.append(" and longitude >= ");
where.append(String.format((Locale) null, "%.6f", lonMin));
where.append(" and longitude <= ");
where.append(String.format((Locale) null, "%.6f", lonMax));
// cacheType limitation
if (cacheType != CacheType.ALL) {
where.append(" and type = \"");
where.append(cacheType.id);
where.append('"');
}
// offline caches only
if (stored) {
where.append(" and reason >= 1");
}
try {
Cursor cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
where.toString(),
null,
null,
null,
null,
"500");
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int index = cursor.getColumnIndex("geocode");
do {
geocodes.add(cursor.getString(index));
} while (cursor.moveToNext());
} else {
cursor.close();
return null;
}
cursor.close();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.loadInViewport: " + e.toString());
}
return geocodes;
}
public List<String> getOfflineAll(CacheType cacheType) {
init();
List<String> geocodes = new ArrayList<String>();
StringBuilder where = new StringBuilder();
// cacheType limitation
if (cacheType != CacheType.ALL) {
where.append(cacheType);
where.append('"');
}
// offline caches only
if (where.length() > 0) {
where.append(" and ");
}
where.append("reason >= 1");
try {
Cursor cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
where.toString(),
null,
null,
null,
null,
"5000");
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int index = cursor.getColumnIndex("geocode");
do {
geocodes.add(cursor.getString(index));
} while (cursor.moveToNext());
} else {
cursor.close();
return null;
}
cursor.close();
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getOfflineAll: " + e.toString());
}
return geocodes;
}
public boolean markFound(String geocode) {
if (StringUtils.isBlank(geocode)) {
return false;
}
init();
boolean result = false;
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("found", 1);
int rows = databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { geocode });
if (rows > 0) {
// update CacheCache
cgCache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
cache.setFound(true);
cacheCache.putCacheInCache(cache);
}
result = true;
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return result;
}
/** delete caches from the DB store 3 days or more before */
public void clean() {
clean(false);
}
/**
* Remove caches with listId = 0
*
* @param more
* true = all caches false = caches stored 3 days or more before
*/
public void clean(boolean more) {
init();
Log.d(Settings.tag, "Database clean: started");
Cursor cursor = null;
Set<String> geocodes = new HashSet<String>();
try {
if (more) {
cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
"reason = 0",
null,
null,
null,
null,
null);
} else {
long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED;
String timestampString = Long.toString(timestamp);
cursor = databaseRO.query(
dbTableCaches,
new String[] { "geocode" },
"reason = 0 and detailed < ? and detailedupdate < ? and visiteddate < ?",
new String[] { timestampString, timestampString, timestampString },
null,
null,
null,
null);
}
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
final int index = cursor.getColumnIndex("geocode");
do {
geocodes.add(cursor.getString(index));
} while (cursor.moveToNext());
}
cursor.close();
}
final int size = geocodes.size();
if (size > 0) {
Log.d(Settings.tag, "Database clean: removing " + size + " geocaches from listId=0");
removeCaches(geocodes, EnumSet.of(RemoveFlag.REMOVE_CACHE));
databaseRW.execSQL("delete from " + dbTableCaches + " where " + cgData.whereGeocodeIn(geocodes));
}
final SQLiteStatement countSql = databaseRO.compileStatement("select count(_id) from " + dbTableCaches + " where reason = 0");
final int count = (int) countSql.simpleQueryForLong();
countSql.close();
Log.d(Settings.tag, "Database clean: " + count + " geocaches remaining for listId=0");
} catch (Exception e) {
Log.w(Settings.tag, "cgData.clean: " + e.toString());
}
Log.d(Settings.tag, "Database clean: finished");
}
/**
* Drop stored list by putting the caches in automatic mode (listId = 0)
*
* @param listId
* the list id to remove the caches from
*/
public void dropList(int listId) {
init();
try {
final ContentValues values = new ContentValues();
values.put("reason", StoredList.TEMPORARY_LIST_ID);
databaseRW.update(dbTableCaches, values, "reason = ?", new String[] { Integer.toString(listId) });
} catch (Exception e) {
Log.e(Settings.tag, "cgData.dropList: error when updating reason", e);
}
}
public void removeAllFromCache() {
// clean up CacheCache
cacheCache.removeAllFromCache();
}
public void removeCache(final String geocode, EnumSet<LoadFlags.RemoveFlag> removeFlags) {
Set<String> geocodes = new HashSet<String>();
geocodes.add(geocode);
removeCaches(geocodes, removeFlags);
}
/**
* Drop caches from the tables they are stored into, as well as the cache files
*
* @param geocodes
* list of geocodes to drop from cache
*/
public void removeCaches(final Set<String> geocodes, EnumSet<LoadFlags.RemoveFlag> removeFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
init();
if (removeFlags.contains(RemoveFlag.REMOVE_CACHE)) {
for (final String geocode : geocodes) {
cacheCache.removeCacheFromCache(geocode);
}
}
if (removeFlags.contains(RemoveFlag.REMOVE_DB)) {
// Drop caches from the database
final ArrayList<String> quotedGeocodes = new ArrayList<String>(geocodes.size());
for (final String geocode : geocodes) {
quotedGeocodes.add('"' + geocode + '"');
}
final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ',');
final String baseWhereClause = "geocode in (" + geocodeList + ")";
databaseRW.beginTransaction();
try {
databaseRW.delete(dbTableCaches, baseWhereClause, null);
databaseRW.delete(dbTableAttributes, baseWhereClause, null);
databaseRW.delete(dbTableSpoilers, baseWhereClause, null);
databaseRW.delete(dbTableLogs, baseWhereClause, null);
databaseRW.delete(dbTableLogCount, baseWhereClause, null);
databaseRW.delete(dbTableLogsOffline, baseWhereClause, null);
databaseRW.delete(dbTableWaypoints, baseWhereClause + " and type <> \"own\"", null);
databaseRW.delete(dbTableTrackables, baseWhereClause, null);
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
// Delete cache directories
for (final String geocode : geocodes) {
cgBase.deleteDirectory(LocalStorage.getStorageDir(geocode));
}
}
}
public boolean saveLogOffline(String geocode, Date date, LogType type, String log) {
if (StringUtils.isBlank(geocode)) {
return false;
}
if (LogType.LOG_UNKNOWN == type && StringUtils.isBlank(log)) {
return false;
}
init();
boolean status = false;
ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", type.id);
values.put("log", log);
values.put("date", date.getTime());
try {
if (hasLogOffline(geocode)) {
final int rows = databaseRW.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode });
if (rows > 0) {
status = true;
}
} else {
final long id = databaseRW.insert(dbTableLogsOffline, null, values);
if (id > 0) {
status = true;
}
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.saveLogOffline: " + e.toString());
}
return status;
}
public cgLog loadLogOffline(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
cgLog log = null;
Cursor cursor = databaseRO.query(
dbTableLogsOffline,
new String[] { "_id", "type", "log", "date" },
"geocode = ?",
new String[] { geocode },
null,
null,
"_id desc",
"1");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
log = new cgLog();
log.id = cursor.getInt(cursor.getColumnIndex("_id"));
log.type = LogType.getById(cursor.getInt(cursor.getColumnIndex("type")));
log.log = cursor.getString(cursor.getColumnIndex("log"));
log.date = cursor.getLong(cursor.getColumnIndex("date"));
}
if (cursor != null) {
cursor.close();
}
return log;
}
public void clearLogOffline(String geocode) {
if (StringUtils.isBlank(geocode)) {
return;
}
init();
databaseRW.delete(dbTableLogsOffline, "geocode = ?", new String[] { geocode });
}
private SQLiteStatement getStatementLogCount() {
return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + dbTableLogsOffline + " WHERE geocode = ?");
}
private synchronized SQLiteStatement getStatement(final String key, final String query) {
SQLiteStatement statement = statements.get(key);
if (statement == null) {
statement = databaseRO.compileStatement(query);
statements.put(key, statement);
}
return statement;
}
private SQLiteStatement getStatementCountStandardList() {
return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID);
}
public boolean hasLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return false;
}
init();
try {
final SQLiteStatement logCount = getStatementLogCount();
synchronized (logCount) {
logCount.bindString(1, geocode);
return logCount.simpleQueryForLong() > 0;
}
} catch (Exception e) {
Log.e(Settings.tag, "cgData.hasLogOffline", e);
}
return false;
}
public void setVisitDate(String geocode, long visitedDate) {
if (StringUtils.isBlank(geocode)) {
return;
}
init();
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("visiteddate", visitedDate);
databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { geocode });
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
}
public List<StoredList> getLists(Resources res) {
init();
List<StoredList> lists = new ArrayList<StoredList>();
lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong()));
try {
String query = "SELECT l._id as _id, l.title as title, COUNT(c._id) as count" +
" FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCaches + " c" +
" ON l._id + " + customListIdOffset + " = c.reason" +
" GROUP BY l._id" +
" ORDER BY l.title COLLATE NOCASE ASC";
Cursor cursor = databaseRO.rawQuery(query, null);
ArrayList<StoredList> storedLists = getListsFromCursor(cursor);
lists.addAll(storedLists);
} catch (Exception e) {
Log.e(Settings.tag, "cgData.readLists: " + e.toString());
}
return lists;
}
private static ArrayList<StoredList> getListsFromCursor(Cursor cursor) {
ArrayList<StoredList> result = new ArrayList<StoredList>();
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int indexId = cursor.getColumnIndex("_id");
int indexTitle = cursor.getColumnIndex("title");
int indexCount = cursor.getColumnIndex("count");
do {
int count = 0;
if (indexCount >= 0) {
count = cursor.getInt(indexCount);
}
StoredList list = new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count);
result.add(list);
} while (cursor.moveToNext());
}
cursor.close();
}
return result;
}
public StoredList getList(int id, Resources res) {
init();
if (id >= customListIdOffset) {
Cursor cursor = databaseRO.query(
dbTableLists,
new String[] { "_id", "title" },
"_id = " + (id - customListIdOffset),
null,
null,
null,
null);
ArrayList<StoredList> lists = getListsFromCursor(cursor);
if (!lists.isEmpty()) {
return lists.get(0);
}
}
// fall back to standard list in case of invalid list id
if (id == StoredList.STANDARD_LIST_ID || id >= customListIdOffset) {
return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong());
}
return null;
}
/**
* Create a new list
*
* @param name
* Name
* @return new listId
*/
public int createList(String name) {
int id = -1;
if (StringUtils.isBlank(name)) {
return id;
}
init();
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
id = (int) databaseRW.insert(dbTableLists, null, values);
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
if (id < 0) {
return -1;
} else {
return (id + customListIdOffset);
}
}
/**
* @param listId
* List to change
* @param name
* New name of list
* @return Number of lists changed
*/
public int renameList(final int listId, final String name) {
if (StringUtils.isBlank(name) || StoredList.STANDARD_LIST_ID == listId) {
return 0;
}
init();
int count = 0;
databaseRW.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
count = databaseRW.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null);
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return count;
}
public boolean removeList(int listId) {
boolean status = false;
if (listId < customListIdOffset) {
return status;
}
init();
databaseRW.beginTransaction();
try {
int cnt = databaseRW.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null);
if (cnt > 0) {
ContentValues values = new ContentValues();
values.put("reason", 1);
databaseRW.update(dbTableCaches, values, "reason = " + listId, null);
status = true;
}
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
return status;
}
public void moveToList(String geocode, int listId) {
if (StringUtils.isBlank(geocode)) {
return;
}
init();
ContentValues values = new ContentValues();
values.put("reason", listId);
databaseRW.beginTransaction();
try {
databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { geocode });
databaseRW.setTransactionSuccessful();
} finally {
databaseRW.endTransaction();
}
// update CacheCache
cgCache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
cache.setListId(listId);
cacheCache.putCacheInCache(cache);
}
}
public synchronized boolean status() {
if (databaseRO == null || databaseRW == null || !initialized) {
return false;
}
return true;
}
public boolean removeSearchedDestination(cgDestination destination) {
boolean success = true;
if (destination == null) {
success = false;
} else {
init();
databaseRW.beginTransaction();
try {
databaseRW.delete(dbTableSearchDestionationHistory, "_id = " + destination.getId(), null);
databaseRW.setTransactionSuccessful();
} catch (Exception e) {
Log.e(Settings.tag, "Unable to remove searched destination", e);
success = false;
} finally {
databaseRW.endTransaction();
}
}
return success;
}
private SQLiteStatement getStatementDescription() {
return getStatement("descriptionFromGeocode", "SELECT description FROM " + dbTableCaches + " WHERE geocode = ?");
}
private SQLiteStatement getStatementCacheId() {
return getStatement("cacheIdFromGeocode", "SELECT cacheid FROM " + dbTableCaches + " WHERE geocode = ?");
}
private SQLiteStatement getStatementGeocode() {
return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?");
}
public String getCacheDescription(String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
try {
final SQLiteStatement description = getStatementDescription();
synchronized (description) {
description.bindString(1, geocode);
return description.simpleQueryForString();
}
} catch (SQLiteDoneException e) {
// Do nothing, it only means we have no information on the cache
} catch (Exception e) {
Log.e(Settings.tag, "cgData.getCacheDescription", e);
}
return null;
}
/**
* checks if this is a newly created database
*
* @return
*/
public static boolean isNewlyCreatedDatebase() {
return newlyCreatedDatabase;
}
/**
* resets flag for newly created database to avoid asking the user multiple times
*/
public static void resetNewlyCreatedDatabase() {
newlyCreatedDatabase = false;
}
private static StringBuilder whereGeocodeIn(Set<String> geocodes) {
final StringBuilder where = new StringBuilder();
if (geocodes != null && geocodes.size() > 0) {
StringBuilder all = new StringBuilder();
for (String geocode : geocodes) {
if (all.length() > 0) {
all.append(", ");
}
all.append('"');
all.append(geocode);
all.append('"');
}
where.append("geocode in (");
where.append(all);
where.append(')');
}
return where;
}
}
|