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
|
package cgeo.geocaching;
import cgeo.calendar.ICalendar;
import cgeo.geocaching.activity.AbstractViewPagerActivity;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.GCConnector;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.GeopointFormatter;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.ui.AbstractCachingPageViewCreator;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.CoordinatesFormatSwitcher;
import cgeo.geocaching.ui.DecryptTextClickListener;
import cgeo.geocaching.ui.EditNoteDialog;
import cgeo.geocaching.ui.EditNoteDialog.EditNoteDialogListener;
import cgeo.geocaching.ui.Formatter;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.LoggingUI;
import cgeo.geocaching.ui.WeakReferenceHandler;
import cgeo.geocaching.utils.BaseUtils;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.ClipboardUtils;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.GeoDirHandler;
import cgeo.geocaching.utils.HtmlUtils;
import cgeo.geocaching.utils.ImageHelper;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MatcherWrapper;
import cgeo.geocaching.utils.RunnableWithArgument;
import cgeo.geocaching.utils.TranslationUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import android.R.color;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* Activity to handle all single-cache-stuff.
*
* e.g. details, description, logs, waypoints, inventory...
*/
public class CacheDetailActivity extends AbstractViewPagerActivity<CacheDetailActivity.Page>
implements EditNoteDialogListener {
private static final int MENU_FIELD_COPY = 1;
private static final int MENU_FIELD_TRANSLATE = 2;
private static final int MENU_FIELD_TRANSLATE_EN = 3;
private static final int MENU_FIELD_SHARE = 4;
private static final int MENU_SHARE = 12;
private static final int MENU_CALENDAR = 11;
private static final int MENU_CACHES_AROUND = 10;
private static final int MENU_BROWSER = 7;
private static final int MENU_DEFAULT_NAVIGATION = 13;
private static final int CONTEXT_MENU_WAYPOINT_EDIT = 1234;
private static final int CONTEXT_MENU_WAYPOINT_DUPLICATE = 1235;
private static final int CONTEXT_MENU_WAYPOINT_DELETE = 1236;
private static final int CONTEXT_MENU_WAYPOINT_NAVIGATE = 1238;
private static final int CONTEXT_MENU_WAYPOINT_CACHES_AROUND = 1239;
private static final int CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION = 1240;
private static final int CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES = 1241;
private static final Pattern DARK_COLOR_PATTERN = Pattern.compile(Pattern.quote("color=\"#") + "(0[0-9]){3}" + "\"");
public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex";
private Geocache cache;
private final Progress progress = new Progress();
private SearchResult search;
private EditNoteDialogListener editNoteDialogListener;
private final GeoDirHandler locationUpdater = new GeoDirHandler() {
@Override
public void updateGeoData(final IGeoData geo) {
if (cacheDistanceView == null) {
return;
}
try {
final StringBuilder dist = new StringBuilder();
if (geo.getCoords() != null && cache != null && cache.getCoords() != null) {
dist.append(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(cache.getCoords())));
}
if (cache != null && cache.getElevation() != null) {
if (geo.getAltitude() != 0.0) {
final float diff = (float) (cache.getElevation() - geo.getAltitude());
dist.append(' ').append(Units.getElevation(diff));
}
}
cacheDistanceView.setText(dist.toString());
cacheDistanceView.bringToFront();
} catch (Exception e) {
Log.w("Failed to update location.");
}
}
};
private CharSequence clickedItemText = null;
private int contextMenuWPIndex = -1;
/**
* If another activity is called and can modify the data of this activity, we refresh it on resume.
*/
private boolean refreshOnResume = false;
// some views that must be available from everywhere // TODO: Reference can block GC?
private TextView cacheDistanceView;
private Handler cacheChangeNotificationHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
notifyDataSetChanged();
}
};
protected ImagesList imagesList;
public CacheDetailActivity() {
// identifier for manual
super("c:geolocation-cache-details");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the main view and set a default title
setTheme();
setContentView(R.layout.cacheview);
setTitle(res.getString(R.string.cache));
String geocode = null;
// TODO Why can it happen that search is not null? onCreate should be called only once and it is not set before.
if (search != null) {
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache != null && cache.getGeocode() != null) {
geocode = cache.getGeocode();
}
}
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = getIntent().getData();
// try to get data from extras
String name = null;
String guid = null;
if (geocode == null && extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
String uriHost = uri.getHost().toLowerCase(Locale.US);
String uriPath = uri.getPath().toLowerCase(Locale.US);
String uriQuery = uri.getQuery();
if (uriQuery != null) {
Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
} else {
Log.i("Opening URI: " + uriHost + uriPath);
}
if (uriHost.contains("geocaching.com")) {
geocode = uri.getQueryParameter("wp");
guid = uri.getQueryParameter("guid");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
} else if (uriHost.contains("coord.info")) {
if (uriPath != null && uriPath.startsWith("/gc")) {
geocode = uriPath.substring(1).toUpperCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
}
// no given data
if (geocode == null && guid == null) {
showToast(res.getString(R.string.err_detail_cache));
finish();
return;
}
final LoadCacheHandler loadCacheHandler = new LoadCacheHandler();
try {
String title = res.getString(R.string.cache);
if (StringUtils.isNotBlank(name)) {
title = name;
} else if (null != geocode && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
title = geocode;
}
progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage());
} catch (Exception e) {
// nothing, we lost the window
}
ImageView defaultNavigationImageView = (ImageView) findViewById(R.id.defaultNavigation);
defaultNavigationImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startDefaultNavigation2();
return true;
}
});
final int pageToOpen = savedInstanceState != null ?
savedInstanceState.getInt(STATE_PAGE_INDEX, 0) :
Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
createViewPager(pageToOpen, new OnPageSelectedListener() {
@Override
public void onPageSelected(int position) {
if (Settings.isOpenLastDetailsPage()) {
Settings.setLastDetailsPage(position);
}
// lazy loading of cache images
if (getPage(position) == Page.IMAGES) {
loadCacheImages();
}
}
});
// Initialization done. Let's load the data with the given information.
new LoadCacheThread(geocode, guid, loadCacheHandler).start();
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_PAGE_INDEX, getCurrentItem());
}
@Override
public void onResume() {
super.onResume();
if (refreshOnResume) {
notifyDataSetChanged();
refreshOnResume = false;
}
locationUpdater.startGeo();
}
@Override
public void onStop() {
if (cache != null) {
cache.setChangeNotificationHandler(null);
}
super.onStop();
}
@Override
public void onPause() {
locationUpdater.stopGeo();
super.onPause();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
contextMenuWPIndex = -1;
switch (viewId) {
case R.id.value: // coordinates, gc-code, name
clickedItemText = ((TextView) view).getText();
String itemTitle = (String) ((TextView) ((View) view.getParent()).findViewById(R.id.name)).getText();
buildOptionsContextmenu(menu, viewId, itemTitle, true);
break;
case R.id.shortdesc:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_description), false);
break;
case R.id.longdesc:
// combine short and long description
String shortDesc = cache.getShortDescription();
if (StringUtils.isBlank(shortDesc)) {
clickedItemText = ((TextView) view).getText();
} else {
clickedItemText = shortDesc + "\n\n" + ((TextView) view).getText();
}
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_description), false);
break;
case R.id.personalnote:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_personal_note), true);
break;
case R.id.hint:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_hint), false);
break;
case R.id.log:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_logs), false);
break;
case -1:
if (null != cache.getWaypoints()) {
try {
final ViewGroup parent = ((ViewGroup) view.getParent());
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i) == view) {
final List<Waypoint> sortedWaypoints = new ArrayList<Waypoint>(cache.getWaypoints());
Collections.sort(sortedWaypoints);
final Waypoint waypoint = sortedWaypoints.get(i);
final int index = cache.getWaypoints().indexOf(waypoint);
menu.setHeaderTitle(res.getString(R.string.waypoint));
if (waypoint.getWaypointType().equals(WaypointType.ORIGINAL)) {
menu.add(CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES, index, 0, R.string.waypoint_reset_cache_coords);
} else {
menu.add(CONTEXT_MENU_WAYPOINT_EDIT, index, 0, R.string.waypoint_edit);
menu.add(CONTEXT_MENU_WAYPOINT_DUPLICATE, index, 0, R.string.waypoint_duplicate);
}
contextMenuWPIndex = index;
if (waypoint.isUserDefined() && !waypoint.getWaypointType().equals(WaypointType.ORIGINAL)) {
menu.add(CONTEXT_MENU_WAYPOINT_DELETE, index, 0, R.string.waypoint_delete);
}
if (waypoint.getCoords() != null) {
menu.add(CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION, index, 0, NavigationAppFactory.getDefaultNavigationApplication().getName());
menu.add(CONTEXT_MENU_WAYPOINT_NAVIGATE, index, 0, R.string.cache_menu_navigate).setIcon(R.drawable.ic_menu_mapmode);
menu.add(CONTEXT_MENU_WAYPOINT_CACHES_AROUND, index, 0, R.string.cache_menu_around);
}
break;
}
}
} catch (Exception e) {
}
}
break;
default:
if (imagesList != null) {
imagesList.onCreateContextMenu(menu, view);
}
break;
}
}
private void buildOptionsContextmenu(ContextMenu menu, int viewId, String fieldTitle, boolean copyOnly) {
menu.setHeaderTitle(fieldTitle);
menu.add(viewId, MENU_FIELD_COPY, 0, res.getString(android.R.string.copy));
if (!copyOnly) {
if (clickedItemText.length() > TranslationUtils.translationTextLengthToWarn) {
showToast(res.getString(R.string.translate_length_warning));
}
menu.add(viewId, MENU_FIELD_TRANSLATE, 0, res.getString(R.string.translate_to_sys_lang, Locale.getDefault().getDisplayLanguage()));
if (Settings.isUseEnglish() && !StringUtils.equals(Locale.getDefault().getLanguage(), Locale.ENGLISH.getLanguage())) {
menu.add(viewId, MENU_FIELD_TRANSLATE_EN, 0, res.getString(R.string.translate_to_english));
}
}
menu.add(viewId, MENU_FIELD_SHARE, 0, res.getString(R.string.cache_share_field));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final int groupId = item.getGroupId();
final int index = item.getItemId();
switch (groupId) {
case R.id.value:
case R.id.shortdesc:
case R.id.longdesc:
case R.id.personalnote:
case R.id.hint:
case R.id.log:
switch (index) {
case MENU_FIELD_COPY:
ClipboardUtils.copyToClipboard(clickedItemText);
showToast(res.getString(R.string.clipboard_copy_ok));
return true;
case MENU_FIELD_TRANSLATE:
TranslationUtils.startActivityTranslate(this, Locale.getDefault().getLanguage(), HtmlUtils.extractText(clickedItemText));
return true;
case MENU_FIELD_TRANSLATE_EN:
TranslationUtils.startActivityTranslate(this, Locale.ENGLISH.getLanguage(), HtmlUtils.extractText(clickedItemText));
return true;
case MENU_FIELD_SHARE:
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, clickedItemText.toString());
startActivity(Intent.createChooser(intent, res.getText(R.string.cache_share_field)));
return true;
default:
break;
}
break;
case CONTEXT_MENU_WAYPOINT_EDIT:
final Waypoint waypointEdit = cache.getWaypoint(index);
if (waypointEdit != null) {
EditWaypointActivity.startActivityEditWaypoint(this, waypointEdit.getId());
refreshOnResume = true;
}
break;
case CONTEXT_MENU_WAYPOINT_DUPLICATE:
final Waypoint waypointDuplicate = cache.getWaypoint(index);
if (cache.duplicateWaypoint(waypointDuplicate)) {
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
notifyDataSetChanged();
}
break;
case CONTEXT_MENU_WAYPOINT_DELETE:
final Waypoint waypointDelete = cache.getWaypoint(index);
if (cache.deleteWaypoint(waypointDelete)) {
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
notifyDataSetChanged();
}
break;
case CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION:
final Waypoint waypointNavigation = cache.getWaypoint(index);
if (waypointNavigation != null) {
NavigationAppFactory.startDefaultNavigationApplication(1, this, waypointNavigation);
}
break;
case CONTEXT_MENU_WAYPOINT_NAVIGATE:
final Waypoint waypointNav = cache.getWaypoint(contextMenuWPIndex);
if (waypointNav != null) {
NavigationAppFactory.showNavigationMenu(this, null, waypointNav, null);
}
break;
case CONTEXT_MENU_WAYPOINT_CACHES_AROUND:
final Waypoint waypointAround = cache.getWaypoint(index);
if (waypointAround != null) {
cgeocaches.startActivityCoordinates(this, waypointAround.getCoords());
}
break;
case CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES:
final Waypoint waypointReset = cache.getWaypoint(index);
if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
createResetCacheCoordinatesDialog(cache, waypointReset).show();
}
else {
final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
new ResetCoordsThread(cache, handler, waypointReset, true, false, progressDialog).start();
}
break;
default:
if (imagesList != null && imagesList.onContextItemSelected(item)) {
return true;
}
return onOptionsItemSelected(item);
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (null != cache) {
menu.add(0, MENU_DEFAULT_NAVIGATION, 0, NavigationAppFactory.getDefaultNavigationApplication().getName()).setIcon(R.drawable.ic_menu_compass); // default navigation tool
final SubMenu subMenu = menu.addSubMenu(0, 0, 0, res.getString(R.string.cache_menu_navigate)).setIcon(R.drawable.ic_menu_mapmode);
NavigationAppFactory.addMenuItems(subMenu, cache);
menu.add(0, MENU_CALENDAR, 0, res.getString(R.string.cache_menu_event)).setIcon(R.drawable.ic_menu_agenda); // add event to calendar
LoggingUI.addMenuItems(menu, cache);
menu.add(0, MENU_CACHES_AROUND, 0, res.getString(R.string.cache_menu_around)).setIcon(R.drawable.ic_menu_rotate); // caches around
menu.add(0, MENU_BROWSER, 0, res.getString(R.string.cache_menu_browser)).setIcon(R.drawable.ic_menu_globe); // browser
menu.add(0, MENU_SHARE, 0, res.getString(R.string.cache_menu_share)).setIcon(R.drawable.ic_menu_share); // share cache
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (cache != null) {
menu.findItem(MENU_DEFAULT_NAVIGATION).setVisible(null != cache.getCoords());
menu.findItem(MENU_CALENDAR).setVisible(cache.canBeAddedToCalendar());
menu.findItem(MENU_CACHES_AROUND).setVisible(null != cache.getCoords() && cache.supportsCachesAround());
menu.findItem(MENU_BROWSER).setVisible(cache.canOpenInBrowser());
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int menuItem = item.getItemId();
switch (menuItem) {
case 0:
// no menu selected, but a new sub menu shown
return false;
case MENU_DEFAULT_NAVIGATION:
startDefaultNavigation();
return true;
case MENU_BROWSER:
cache.openInBrowser(this);
return true;
case MENU_CACHES_AROUND:
cgeocaches.startActivityCoordinates(this, cache.getCoords());
return true;
case MENU_CALENDAR:
addToCalendarWithIntent();
return true;
case MENU_SHARE:
if (cache != null) {
cache.shareCache(this, res);
return true;
}
return false;
default:
if (NavigationAppFactory.onMenuItemSelected(item, this, cache)) {
return true;
}
if (LoggingUI.onMenuItemSelected(item, this, cache)) {
refreshOnResume = true;
return true;
}
}
return true;
}
private class LoadCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(final Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
if (search == null) {
showToast(res.getString(R.string.err_dwld_details_failed));
progress.dismiss();
finish();
return;
}
if (search.getError() != null) {
showToast(res.getString(R.string.err_dwld_details_failed) + " " + search.getError().getErrorString(res) + ".");
progress.dismiss();
finish();
return;
}
updateStatusMsg(res.getString(R.string.cache_dialog_loading_details_status_render));
// Data loaded, we're ready to show it!
notifyDataSetChanged();
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_loading_details)
+ "\n\n"
+ msg);
}
@Override
public void handleCancel(final Object extra) {
finish();
}
}
private void notifyDataSetChanged() {
if (search == null) {
return;
}
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache == null) {
progress.dismiss();
showToast(res.getString(R.string.err_detail_cache_find_some));
finish();
return;
}
// allow cache to notify CacheDetailActivity when it changes so it can be reloaded
cache.setChangeNotificationHandler(cacheChangeNotificationHandler);
// action bar: title and icon
if (StringUtils.isNotBlank(cache.getName())) {
setTitle(cache.getName() + " (" + cache.getGeocode() + ')');
} else {
setTitle(cache.getGeocode());
}
((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cache.getType().markerId), null, null, null);
reinitializeViewPager();
// rendering done! remove progress popup if any there
invalidateOptionsMenuCompatible();
progress.dismiss();
}
/**
* Loads the cache with the given geocode or guid.
*/
private class LoadCacheThread extends Thread {
private CancellableHandler handler = null;
private String geocode;
private String guid;
public LoadCacheThread(final String geocode, final String guid, final CancellableHandler handlerIn) {
handler = handlerIn;
if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
showToast(res.getString(R.string.err_detail_cache_forgot));
progress.dismiss();
finish();
return;
}
this.geocode = geocode;
this.guid = guid;
}
@Override
public void run() {
search = Geocache.searchByGeocode(geocode, StringUtils.isBlank(geocode) ? guid : null, 0, false, handler);
handler.sendMessage(Message.obtain());
}
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context
* The application's environment.
* @param action
* The Intent action to check for availability.
* @param uri
* The Intent URI to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
private static boolean isIntentAvailable(Context context, String action, Uri uri) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent;
if (uri == null) {
intent = new Intent(action);
} else {
intent = new Intent(action, uri);
}
final List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return !list.isEmpty();
}
private void addToCalendarWithIntent() {
final boolean calendarAddOnAvailable = isIntentAvailable(this, ICalendar.INTENT, Uri.parse(ICalendar.URI_SCHEME + "://" + ICalendar.URI_HOST));
if (calendarAddOnAvailable) {
final Parameters params = new Parameters(
ICalendar.PARAM_NAME, cache.getName(),
ICalendar.PARAM_NOTE, StringUtils.defaultString(cache.getPersonalNote()),
ICalendar.PARAM_HIDDEN_DATE, String.valueOf(cache.getHiddenDate().getTime()),
ICalendar.PARAM_URL, StringUtils.defaultString(cache.getUrl()),
ICalendar.PARAM_COORDS, cache.getCoords() == null ? "" : cache.getCoords().format(GeopointFormatter.Format.LAT_LON_DECMINUTE_RAW),
ICalendar.PARAM_LOCATION, StringUtils.defaultString(cache.getLocation()),
ICalendar.PARAM_SHORT_DESC, StringUtils.defaultString(cache.getShortDescription()),
ICalendar.PARAM_START_TIME_MINUTES, StringUtils.defaultString(cache.guessEventTimeMinutes())
);
startActivity(new Intent(ICalendar.INTENT,
Uri.parse(ICalendar.URI_SCHEME + "://" + ICalendar.URI_HOST + "?" + params.toString())));
} else {
// Inform user the calendar add-on is not installed and let them get it from Google Play
new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.addon_missing_title))
.setMessage(new StringBuilder(res.getString(R.string.helper_calendar_missing))
.append(' ')
.append(res.getString(R.string.addon_download_prompt))
.toString())
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(ICalendar.CALENDAR_ADDON_URI));
startActivity(intent);
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
private void startDefaultNavigation() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, cache);
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
private void startDefaultNavigation2() {
NavigationAppFactory.startDefaultNavigationApplication(2, this, cache);
}
/**
* Wrapper for the referenced method in the xml-layout.
*/
public void startDefaultNavigation(@SuppressWarnings("unused") View view) {
startDefaultNavigation();
}
/**
* referenced from XML view
*/
public void showNavigationMenu(@SuppressWarnings("unused") View view) {
NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true);
}
/**
* Listener for clicks on username
*/
private class UserActionsClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == null) {
return;
}
if (!cache.supportsUserActions()) {
return;
}
clickedItemText = ((TextView) view).getText().toString();
showUserActionsDialog(clickedItemText);
}
}
/**
* Listener for clicks on owner name
*/
private class OwnerActionsClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == null) {
return;
}
if (!cache.supportsUserActions()) {
return;
}
// Use real owner name vice the one owner chose to display
if (StringUtils.isNotBlank(cache.getOwnerUserId())) {
clickedItemText = cache.getOwnerUserId();
} else {
clickedItemText = ((TextView) view).getText().toString();
}
showUserActionsDialog(clickedItemText);
}
}
/**
* Opens a dialog to do actions on an username
*/
private void showUserActionsDialog(final CharSequence name) {
final CharSequence[] items = { res.getString(R.string.user_menu_view_hidden),
res.getString(R.string.user_menu_view_found),
res.getString(R.string.user_menu_open_browser),
res.getString(R.string.user_menu_send_message)
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(res.getString(R.string.user_menu_title) + " " + name);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
cgeocaches.startActivityOwner(CacheDetailActivity.this, name.toString());
return;
case 1:
cgeocaches.startActivityUserName(CacheDetailActivity.this, name.toString());
return;
case 2:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + Network.encode(name.toString()))));
return;
case 3:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/email/?u=" + Network.encode(name.toString()))));
return;
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void loadCacheImages() {
if (imagesList != null) {
return;
}
PageViewCreator creator = getViewCreator(Page.IMAGES);
if (creator == null) {
return;
}
View imageView = creator.getView();
if (imageView == null) {
return;
}
imagesList = new ImagesList(this, cache.getGeocode());
imagesList.loadImages(imageView, cache.getImages(), false);
}
public static void startActivity(final Context context, final String geocode) {
final Intent detailIntent = new Intent(context, CacheDetailActivity.class);
detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
context.startActivity(detailIntent);
}
/**
* Enum of all possible pages with methods to get the view and a title.
*/
public enum Page {
DETAILS(R.string.detail),
DESCRIPTION(R.string.cache_description),
LOGS(R.string.cache_logs),
LOGSFRIENDS(R.string.cache_logsfriends),
WAYPOINTS(R.string.cache_waypoints),
INVENTORY(R.string.cache_inventory),
IMAGES(R.string.cache_images);
final private int titleStringId;
Page(final int titleStringId) {
this.titleStringId = titleStringId;
}
}
private class AttributeViewBuilder {
private ViewGroup attributeIconsLayout; // layout for attribute icons
private ViewGroup attributeDescriptionsLayout; // layout for attribute descriptions
private boolean attributesShowAsIcons = true; // default: show icons
/**
* If the cache is from a non GC source, it might be without icons. Disable switching in those cases.
*/
private boolean noAttributeIconsFound = false;
private int attributeBoxMaxWidth;
public void fillView(final LinearLayout attributeBox) {
// first ensure that the view is empty
attributeBox.removeAllViews();
// maximum width for attribute icons is screen width - paddings of parents
attributeBoxMaxWidth = Compatibility.getDisplayWidth();
ViewParent child = attributeBox;
do {
if (child instanceof View) {
attributeBoxMaxWidth -= ((View) child).getPaddingLeft() + ((View) child).getPaddingRight();
}
child = child.getParent();
} while (child != null);
// delete views holding description / icons
attributeDescriptionsLayout = null;
attributeIconsLayout = null;
attributeBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// toggle between attribute icons and descriptions
toggleAttributeDisplay(attributeBox, attributeBoxMaxWidth);
}
});
// icons or text?
//
// also show icons when noAttributeImagesFound == true. Explanation:
// 1. no icons could be found in the first invocation of this method
// 2. user refreshes cache from web
// 3. now this method is called again
// 4. attributeShowAsIcons is false but noAttributeImagesFound is true
// => try to show them now
if (attributesShowAsIcons || noAttributeIconsFound) {
showAttributeIcons(attributeBox, attributeBoxMaxWidth);
} else {
showAttributeDescriptions(attributeBox);
}
}
/**
* lazy-creates the layout holding the icons of the caches attributes
* and makes it visible
*/
private void showAttributeIcons(LinearLayout attribBox, int parentWidth) {
if (attributeIconsLayout == null) {
attributeIconsLayout = createAttributeIconsLayout(parentWidth);
// no matching icons found? show text
if (noAttributeIconsFound) {
showAttributeDescriptions(attribBox);
return;
}
}
attribBox.removeAllViews();
attribBox.addView(attributeIconsLayout);
attributesShowAsIcons = true;
}
/**
* lazy-creates the layout holding the descriptions of the caches attributes
* and makes it visible
*/
private void showAttributeDescriptions(LinearLayout attribBox) {
if (attributeDescriptionsLayout == null) {
attributeDescriptionsLayout = createAttributeDescriptionsLayout();
}
attribBox.removeAllViews();
attribBox.addView(attributeDescriptionsLayout);
attributesShowAsIcons = false;
}
/**
* toggle attribute descriptions and icons
*/
private void toggleAttributeDisplay(LinearLayout attribBox, int parentWidth) {
// Don't toggle when there are no icons to show.
if (noAttributeIconsFound) {
return;
}
// toggle
if (attributesShowAsIcons) {
showAttributeDescriptions(attribBox);
} else {
showAttributeIcons(attribBox, parentWidth);
}
}
private ViewGroup createAttributeIconsLayout(int parentWidth) {
final LinearLayout rows = new LinearLayout(CacheDetailActivity.this);
rows.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
rows.setOrientation(LinearLayout.VERTICAL);
LinearLayout attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
noAttributeIconsFound = true;
for (String attributeName : cache.getAttributes()) {
// check if another attribute icon fits in this row
attributeRow.measure(0, 0);
int rowWidth = attributeRow.getMeasuredWidth();
FrameLayout fl = (FrameLayout) getLayoutInflater().inflate(R.layout.attribute_image, null);
ImageView iv = (ImageView) fl.getChildAt(0);
if ((parentWidth - rowWidth) < iv.getLayoutParams().width) {
// make a new row
attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
}
final boolean strikethru = !CacheAttribute.isEnabled(attributeName);
final CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib != null) {
noAttributeIconsFound = false;
Drawable d = res.getDrawable(attrib.drawableId);
iv.setImageDrawable(d);
// strike through?
if (strikethru) {
// generate strikethru image with same properties as attribute image
ImageView strikethruImage = new ImageView(CacheDetailActivity.this);
strikethruImage.setLayoutParams(iv.getLayoutParams());
d = res.getDrawable(R.drawable.attribute__strikethru);
strikethruImage.setImageDrawable(d);
fl.addView(strikethruImage);
}
} else {
Drawable d = res.getDrawable(R.drawable.attribute_unknown);
iv.setImageDrawable(d);
}
attributeRow.addView(fl);
}
return rows;
}
private LinearLayout newAttributeIconsRow() {
LinearLayout rowLayout = new LinearLayout(CacheDetailActivity.this);
rowLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
return rowLayout;
}
private ViewGroup createAttributeDescriptionsLayout() {
final LinearLayout descriptions = (LinearLayout) getLayoutInflater().inflate(
R.layout.attribute_descriptions, null);
final TextView attribView = (TextView) descriptions.getChildAt(0);
final StringBuilder buffer = new StringBuilder();
for (String attributeName : cache.getAttributes()) {
final boolean enabled = CacheAttribute.isEnabled(attributeName);
// search for a translation of the attribute
CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib == null) {
attrib = CacheAttribute.UNKNOWN;
}
attributeName = attrib.getL10n(enabled);
if (buffer.length() > 0) {
buffer.append('\n');
}
buffer.append(attributeName);
}
attribView.setText(buffer);
return descriptions;
}
}
/**
* Creator for details-view.
*/
private class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
/**
* Reference to the details list, so that the helper-method can access it without an additional argument
*/
private LinearLayout detailsList;
// TODO Do we need this thread-references?
private StoreCacheThread storeThread;
private RefreshCacheThread refreshThread;
private Thread watchlistThread;
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_details, null);
// Start loading preview map
if (Settings.isStoreOfflineMaps()) {
new PreviewMapTask().execute((Void) null);
}
detailsList = (LinearLayout) view.findViewById(R.id.details_list);
final CacheDetailsCreator details = new CacheDetailsCreator(CacheDetailActivity.this, detailsList);
// cache name (full name)
Spannable span = (new Spannable.Factory()).newSpannable(Html.fromHtml(cache.getName()).toString());
if (cache.isDisabled() || cache.isArchived()) { // strike
span.setSpan(new StrikethroughSpan(), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (cache.isArchived()) {
span.setSpan(new ForegroundColorSpan(res.getColor(R.color.archived_cache_color)), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
registerForContextMenu(details.add(R.string.cache_name, span));
details.add(R.string.cache_type, cache.getType().getL10n());
details.addSize(cache);
registerForContextMenu(details.add(R.string.cache_geocode, cache.getGeocode()));
details.addCacheState(cache);
details.addDistance(cache, cacheDistanceView);
cacheDistanceView = details.getValueView();
details.addDifficulty(cache);
details.addTerrain(cache);
details.addRating(cache);
// favorite count
if (cache.getFavoritePoints() > 0) {
details.add(R.string.cache_favourite, cache.getFavoritePoints() + "×");
}
// own rating
if (cache.getMyVote() > 0) {
details.addStars(R.string.cache_own_rating, cache.getMyVote());
}
// cache author
if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) {
TextView ownerView = details.add(R.string.cache_owner, "");
if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) {
ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE);
} else { // OwnerReal guaranteed to be not blank based on above
ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE);
}
ownerView.setOnClickListener(new OwnerActionsClickListener());
}
// cache hidden
if (cache.getHiddenDate() != null) {
long time = cache.getHiddenDate().getTime();
if (time > 0) {
String dateString = Formatter.formatFullDate(time);
if (cache.isEventCache()) {
dateString = DateUtils.formatDateTime(cgeoapplication.getInstance().getBaseContext(), time, DateUtils.FORMAT_SHOW_WEEKDAY) + ", " + dateString;
}
details.add(cache.isEventCache() ? R.string.cache_event : R.string.cache_hidden, dateString);
}
}
// cache location
if (StringUtils.isNotBlank(cache.getLocation())) {
details.add(R.string.cache_location, cache.getLocation());
}
// cache coordinates
if (cache.getCoords() != null) {
TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString());
valueView.setOnClickListener(new CoordinatesFormatSwitcher(cache.getCoords()));
registerForContextMenu(valueView);
}
// cache attributes
if (!cache.getAttributes().isEmpty()) {
new AttributeViewBuilder().fillView((LinearLayout) view.findViewById(R.id.attributes_innerbox));
view.findViewById(R.id.attributes_box).setVisibility(View.VISIBLE);
}
updateOfflineBox(view, cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener());
// watchlist
Button buttonWatchlistAdd = (Button) view.findViewById(R.id.add_to_watchlist);
Button buttonWatchlistRemove = (Button) view.findViewById(R.id.remove_from_watchlist);
buttonWatchlistAdd.setOnClickListener(new AddToWatchlistClickListener());
buttonWatchlistRemove.setOnClickListener(new RemoveFromWatchlistClickListener());
updateWatchlistBox();
// favorite points
Button buttonFavPointAdd = (Button) view.findViewById(R.id.add_to_favpoint);
Button buttonFavPointRemove = (Button) view.findViewById(R.id.remove_from_favpoint);
buttonFavPointAdd.setOnClickListener(new FavoriteAddClickListener());
buttonFavPointRemove.setOnClickListener(new FavoriteRemoveClickListener());
updateFavPointBox();
// list
Button buttonChangeList = (Button) view.findViewById(R.id.change_list);
buttonChangeList.setOnClickListener(new ChangeListClickListener());
updateListBox();
// data license
IConnector connector = ConnectorFactory.getConnector(cache);
if (connector != null) {
String license = connector.getLicenseText(cache);
if (StringUtils.isNotBlank(license)) {
view.findViewById(R.id.license_box).setVisibility(View.VISIBLE);
TextView licenseView = ((TextView) view.findViewById(R.id.license));
licenseView.setText(Html.fromHtml(license), BufferType.SPANNABLE);
licenseView.setClickable(true);
licenseView.setMovementMethod(LinkMovementMethod.getInstance());
} else {
view.findViewById(R.id.license_box).setVisibility(View.GONE);
}
}
return view;
}
private class StoreCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
storeThread = null;
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_offline_save_message)
+ "\n\n"
+ msg);
}
}
private class RefreshCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
refreshThread = null;
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_refresh_message)
+ "\n\n"
+ msg);
}
}
private class DropCacheHandler extends Handler {
@Override
public void handleMessage(Message msg) {
CacheDetailActivity.this.notifyDataSetChanged();
}
}
private class StoreCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title,
new RunnableWithArgument<Integer>() {
@Override
public void run(final Integer selectedListId) {
storeCache(selectedListId);
}
}, true, StoredList.TEMPORARY_LIST_ID);
} else {
storeCache(StoredList.TEMPORARY_LIST_ID);
}
}
protected void storeCache(int listId) {
final StoreCacheHandler storeCacheHandler = new StoreCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage());
if (storeThread != null) {
storeThread.interrupt();
}
storeThread = new StoreCacheThread(listId, storeCacheHandler);
storeThread.start();
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isNetworkConnected(getApplicationContext())) {
showToast(getString(R.string.err_server));
return;
}
final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage());
if (refreshThread != null) {
refreshThread.interrupt();
}
refreshThread = new RefreshCacheThread(refreshCacheHandler);
refreshThread.start();
}
}
private class StoreCacheThread extends Thread {
final private int listId;
final private CancellableHandler handler;
public StoreCacheThread(final int listId, final CancellableHandler handler) {
this.listId = listId;
this.handler = handler;
}
@Override
public void run() {
cache.store(listId, handler);
}
}
private class RefreshCacheThread extends Thread {
final private CancellableHandler handler;
public RefreshCacheThread(final CancellableHandler handler) {
this.handler = handler;
}
@Override
public void run() {
cache.refresh(cache.getListId(), handler);
handler.sendEmptyMessage(0);
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
final DropCacheHandler dropCacheHandler = new DropCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
new DropCacheThread(dropCacheHandler).start();
}
}
private class DropCacheThread extends Thread {
private Handler handler = null;
public DropCacheThread(Handler handlerIn) {
handler = handlerIn;
}
@Override
public void run() {
cache.drop(handler);
}
}
/**
* Abstract Listener for add / remove buttons for watchlist
*/
private abstract class AbstractWatchlistClickListener implements View.OnClickListener {
public void doExecute(int titleId, int messageId, Thread thread) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_watchlist_still_managing));
return;
}
progress.show(CacheDetailActivity.this, res.getString(titleId), res.getString(messageId), true, null);
if (watchlistThread != null) {
watchlistThread.interrupt();
}
watchlistThread = thread;
watchlistThread.start();
}
}
/**
* Listener for "add to watchlist" button
*/
private class AddToWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_watchlist_add_title,
R.string.cache_dialog_watchlist_add_message,
new WatchlistAddThread(new WatchlistHandler()));
}
}
/**
* Listener for "remove from watchlist" button
*/
private class RemoveFromWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_watchlist_remove_title,
R.string.cache_dialog_watchlist_remove_message,
new WatchlistRemoveThread(new WatchlistHandler()));
}
}
/** Thread to add this cache to the watchlist of the user */
private class WatchlistAddThread extends Thread {
private final Handler handler;
public WatchlistAddThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.addToWatchlist(cache) ? 1 : -1);
}
}
/** Thread to remove this cache from the watchlist of the user */
private class WatchlistRemoveThread extends Thread {
private final Handler handler;
public WatchlistRemoveThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.removeFromWatchlist(cache) ? 1 : -1);
}
}
/** Thread to add this cache to the favourite list of the user */
private class FavoriteAddThread extends Thread {
private final Handler handler;
public FavoriteAddThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.addToFavorites(cache) ? 1 : -1);
}
}
/** Thread to remove this cache to the favourite list of the user */
private class FavoriteRemoveThread extends Thread {
private final Handler handler;
public FavoriteRemoveThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.removeFromFavorites(cache) ? 1 : -1);
}
}
private class FavoriteUpdateHandler extends Handler {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
if (msg.what == -1) {
showToast(res.getString(R.string.err_favorite_failed));
} else {
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
}
/**
* Listener for "add to favourites" button
*/
private class FavoriteAddClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_favourite_add_title,
R.string.cache_dialog_favourite_add_message,
new FavoriteAddThread(new FavoriteUpdateHandler()));
}
}
/**
* Listener for "remove from favourites" button
*/
private class FavoriteRemoveClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_favourite_remove_title,
R.string.cache_dialog_favourite_remove_message,
new FavoriteRemoveThread(new FavoriteUpdateHandler()));
}
}
/**
* Listener for "change list" button
*/
private class ChangeListClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title,
new RunnableWithArgument<Integer>() {
@Override
public void run(final Integer selectedListId) {
switchListById(selectedListId);
}
}, true, cache.getListId());
}
}
/**
* move cache to another list
*
* @param listId
* the ID of the list
*/
public void switchListById(int listId) {
if (listId < 0) {
return;
}
Settings.saveLastList(listId);
cgData.moveToList(cache, listId);
updateListBox();
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateWatchlistBox() {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.watchlist_box);
boolean supportsWatchList = cache.supportsWatchList();
layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE);
if (!supportsWatchList) {
return;
}
Button buttonAdd = (Button) view.findViewById(R.id.add_to_watchlist);
Button buttonRemove = (Button) view.findViewById(R.id.remove_from_watchlist);
TextView text = (TextView) view.findViewById(R.id.watchlist_text);
if (cache.isOnWatchlist() || cache.isOwner()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_watchlist_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_watchlist_not_on);
}
// the owner of a cache has it always on his watchlist. Adding causes an error
if (cache.isOwner()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateFavPointBox() {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.favpoint_box);
boolean supportsFavoritePoints = cache.supportsFavoritePoints();
layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE);
if (!supportsFavoritePoints || cache.isOwner() || !Settings.isPremiumMember()) {
return;
}
Button buttonAdd = (Button) view.findViewById(R.id.add_to_favpoint);
Button buttonRemove = (Button) view.findViewById(R.id.remove_from_favpoint);
TextView text = (TextView) view.findViewById(R.id.favpoint_text);
if (cache.isFavorite()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_favpoint_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_favpoint_not_on);
}
// Add/remove to Favorites is only possible if the cache has been found
if (!cache.isFound()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides/updates list box
*/
private void updateListBox() {
View box = view.findViewById(R.id.list_box);
if (cache.isOffline()) {
// show box
box.setVisibility(View.VISIBLE);
// update text
TextView text = (TextView) view.findViewById(R.id.list_text);
StoredList list = cgData.getList(cache.getListId());
if (list != null) {
text.setText(res.getString(R.string.cache_list_text) + " " + list.title);
} else {
// this should not happen
text.setText(R.string.cache_list_unknown);
}
} else {
// hide box
box.setVisibility(View.GONE);
}
}
/**
* Handler, called when watchlist add or remove is done
*/
private class WatchlistHandler extends Handler {
@Override
public void handleMessage(Message msg) {
watchlistThread = null;
progress.dismiss();
if (msg.what == -1) {
showToast(res.getString(R.string.err_watchlist_failed));
} else {
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
}
private class PreviewMapTask extends AsyncTask<Void, Void, BitmapDrawable> {
@Override
protected BitmapDrawable doInBackground(Void... parameters) {
try {
// persistent preview from storage
Bitmap image = decode(cache);
if (image == null) {
StaticMapsProvider.storeCachePreviewMap(cache);
image = decode(cache);
if (image == null) {
return null;
}
}
return ImageHelper.scaleBitmapToFitDisplay(image);
} catch (Exception e) {
Log.w("CacheDetailActivity.PreviewMapTask", e);
return null;
}
}
private Bitmap decode(final Geocache cache) {
return StaticMapsProvider.getPreviewMap(cache.getGeocode());
}
@Override
protected void onPostExecute(BitmapDrawable image) {
if (image == null) {
return;
}
try {
final Bitmap bitmap = image.getBitmap();
if (bitmap == null || bitmap.getWidth() <= 10) {
return;
}
((ImageView) view.findViewById(R.id.map_preview)).setImageDrawable(image);
view.findViewById(R.id.map_preview_box).setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("CacheDetailActivity.PreviewMapTask", e);
}
}
}
}
private class DescriptionViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_description, null);
// cache short description
if (StringUtils.isNotBlank(cache.getShortDescription())) {
new LoadDescriptionTask(cache.getShortDescription(), view.findViewById(R.id.shortdesc), null, null).execute();
}
// long description
if (StringUtils.isNotBlank(cache.getDescription())) {
if (Settings.isAutoLoadDescription()) {
loadLongDescription();
} else {
Button showDesc = (Button) view.findViewById(R.id.show_description);
showDesc.setVisibility(View.VISIBLE);
showDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
loadLongDescription();
}
});
}
}
// cache personal note
final TextView personalNoteView = (TextView) view.findViewById(R.id.personalnote);
setPersonalNote(personalNoteView);
personalNoteView.setMovementMethod(LinkMovementMethod.getInstance());
registerForContextMenu(personalNoteView);
final Button personalNoteEdit = (Button) view.findViewById(R.id.edit_personalnote);
if (cache.isOffline()) {
personalNoteEdit.setVisibility(View.VISIBLE);
personalNoteEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editNoteDialogListener = new EditNoteDialogListener() {
@Override
public void onFinishEditNoteDialog(final String note) {
cache.setPersonalNote(note);
setPersonalNote(personalNoteView);
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); }
};
final FragmentManager fm = getSupportFragmentManager();
final EditNoteDialog dialog = new EditNoteDialog(cache.getPersonalNote());
dialog.show(fm, "fragment_edit_note");
}
});
} else {
personalNoteEdit.setVisibility(View.INVISIBLE);
}
// cache hint and spoiler images
final View hintBoxView = view.findViewById(R.id.hint_box);
if (StringUtils.isNotBlank(cache.getHint()) || CollectionUtils.isNotEmpty(cache.getSpoilers())) {
hintBoxView.setVisibility(View.VISIBLE);
} else {
hintBoxView.setVisibility(View.GONE);
}
final TextView hintView = ((TextView) view.findViewById(R.id.hint));
if (StringUtils.isNotBlank(cache.getHint())) {
if (BaseUtils.containsHtml(cache.getHint())) {
hintView.setText(Html.fromHtml(cache.getHint(), new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null), TextView.BufferType.SPANNABLE);
hintView.setText(CryptUtils.rot13((Spannable) hintView.getText()));
}
else {
hintView.setText(CryptUtils.rot13(cache.getHint()));
}
hintView.setVisibility(View.VISIBLE);
hintView.setClickable(true);
hintView.setOnClickListener(new DecryptTextClickListener());
registerForContextMenu(hintView);
} else {
hintView.setVisibility(View.GONE);
hintView.setClickable(false);
hintView.setOnClickListener(null);
}
final TextView spoilerlinkView = ((TextView) view.findViewById(R.id.hint_spoilerlink));
if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
spoilerlinkView.setVisibility(View.VISIBLE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) {
showToast(res.getString(R.string.err_detail_no_spoiler));
return;
}
ImagesActivity.startActivitySpoilerImages(CacheDetailActivity.this, cache.getGeocode(), cache.getSpoilers());
}
});
} else {
spoilerlinkView.setVisibility(View.GONE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(null);
}
return view;
}
private void setPersonalNote(final TextView personalNoteView) {
final String personalNote = cache.getPersonalNote();
personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE);
if (StringUtils.isNotBlank(personalNote)) {
personalNoteView.setVisibility(View.VISIBLE);
} else {
personalNoteView.setVisibility(View.GONE);
}
}
private void loadLongDescription() {
Button showDesc = (Button) view.findViewById(R.id.show_description);
showDesc.setVisibility(View.GONE);
showDesc.setOnClickListener(null);
view.findViewById(R.id.loading).setVisibility(View.VISIBLE);
new LoadDescriptionTask(cache.getDescription(), view.findViewById(R.id.longdesc), view.findViewById(R.id.loading), view.findViewById(R.id.shortdesc)).execute();
}
}
@Override
public void onFinishEditNoteDialog(final String note) {
editNoteDialogListener.onFinishEditNoteDialog(note);
}
private static class HtmlImageCounter implements Html.ImageGetter {
private int imageCount = 0;
@Override
public Drawable getDrawable(String url) {
imageCount++;
return null;
}
public int getImageCount() {
return imageCount;
}
}
/**
* Loads the description in background. <br />
* <br />
* Params:
* <ol>
* <li>description string (String)</li>
* <li>target description view (TextView)</li>
* <li>loading indicator view (View, may be null)</li>
* </ol>
*/
private class LoadDescriptionTask extends AsyncTask<Object, Void, Void> {
private final View loadingIndicatorView;
private final TextView descriptionView;
private final String descriptionString;
private Spanned description;
private final View shortDescView;
public LoadDescriptionTask(final String description, final View descriptionView, final View loadingIndicatorView, final View shortDescView) {
this.descriptionString = description;
this.descriptionView = (TextView) descriptionView;
this.loadingIndicatorView = loadingIndicatorView;
this.shortDescView = shortDescView;
}
@Override
protected Void doInBackground(Object... params) {
try {
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
description = Html.fromHtml(descriptionString, imageCounter, unknownTagsHandler);
publishProgress();
boolean needsRefresh = false;
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
description = Html.fromHtml(descriptionString, new HtmlImage(cache.getGeocode(), true, cache.getListId(), false), unknownTagsHandler);
needsRefresh = true;
}
// If description has an HTML construct which may be problematic to render, add a note at the end of the long description.
// Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though
// sometimes technically incorrect.
if (unknownTagsHandler.isProblematicDetected() && descriptionView != null) {
final int startPos = description.length();
final IConnector connector = ConnectorFactory.getConnector(cache);
final Spanned tableNote = Html.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"));
((Editable) description).append("\n\n").append(tableNote);
((Editable) description).setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
needsRefresh = true;
}
if (needsRefresh) {
publishProgress();
}
} catch (Exception e) {
Log.e("LoadDescriptionTask: ", e);
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
if (description == null) {
showToast(res.getString(R.string.err_load_descr_failed));
return;
}
if (StringUtils.isNotBlank(descriptionString)) {
descriptionView.setText(description, TextView.BufferType.SPANNABLE);
descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
fixBlackTextColor(descriptionView, descriptionString);
descriptionView.setVisibility(View.VISIBLE);
registerForContextMenu(descriptionView);
hideDuplicatedShortDescription();
}
}
/**
* Hide the short description, if it is contained somewhere at the start of the long description.
*/
private void hideDuplicatedShortDescription() {
if (shortDescView != null) {
final String shortDescription = cache.getShortDescription();
if (StringUtils.isNotBlank(shortDescription)) {
int index = descriptionString.indexOf(shortDescription);
if (index >= 0 && index < 200) {
shortDescView.setVisibility(View.GONE);
}
}
}
}
@Override
protected void onPostExecute(Void result) {
if (null != loadingIndicatorView) {
loadingIndicatorView.setVisibility(View.GONE);
}
}
/**
* handle caches with black font color
*
* @param view
* @param text
*/
private void fixBlackTextColor(final TextView view, final String text) {
if (Settings.isLightSkin()) {
return;
}
int backcolor = color.black;
if (-1 != StringUtils.indexOfAny(text, new String[] { "color=\"black", "color=\"#000080\"" })) {
backcolor = color.darker_gray;
}
else {
MatcherWrapper matcher = new MatcherWrapper(DARK_COLOR_PATTERN, text);
if (matcher.find()) {
backcolor = color.darker_gray;
}
}
view.setBackgroundResource(backcolor);
}
}
private class LogsViewCreator extends AbstractCachingPageViewCreator<ListView> {
private final boolean allLogs;
LogsViewCreator(boolean allLogs) {
this.allLogs = allLogs;
}
@Override
public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_logs, null);
// log count
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (logCounts != null) {
final List<Entry<LogType, Integer>> sortedLogCounts = new ArrayList<Entry<LogType, Integer>>(logCounts.size());
for (Entry<LogType, Integer> entry : logCounts.entrySet()) {
// it may happen that the label is unknown -> then avoid any output for this type
if (entry.getKey() != LogType.PUBLISH_LISTING && entry.getKey().getL10n() != null) {
sortedLogCounts.add(entry);
}
}
if (!sortedLogCounts.isEmpty()) {
// sort the log counts by type id ascending. that way the FOUND, DNF log types are the first and most visible ones
Collections.sort(sortedLogCounts, new Comparator<Entry<LogType, Integer>>() {
@Override
public int compare(Entry<LogType, Integer> logCountItem1, Entry<LogType, Integer> logCountItem2) {
return logCountItem1.getKey().compareTo(logCountItem2.getKey());
}
});
ArrayList<String> labels = new ArrayList<String>(sortedLogCounts.size());
for (Entry<LogType, Integer> pair : sortedLogCounts) {
labels.add(pair.getValue() + "× " + pair.getKey().getL10n());
}
final TextView countView = new TextView(CacheDetailActivity.this);
countView.setText(res.getString(R.string.cache_log_types) + ": " + StringUtils.join(labels, ", "));
view.addHeaderView(countView, null, false);
}
}
final List<LogEntry> logs = allLogs ? cache.getLogs() : cache.getFriendsLogs();
view.setAdapter(new ArrayAdapter<LogEntry>(CacheDetailActivity.this, R.layout.cacheview_logs_item, logs) {
final UserActionsClickListener userActionsClickListener = new UserActionsClickListener();
final DecryptTextClickListener decryptTextClickListener = new DecryptTextClickListener();
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.cacheview_logs_item, null);
}
LogViewHolder holder = (LogViewHolder) rowView.getTag();
if (null == holder) {
holder = new LogViewHolder(rowView);
rowView.setTag(holder);
}
final LogEntry log = getItem(position);
if (log.date > 0) {
holder.date.setText(Formatter.formatShortDate(log.date));
holder.date.setVisibility(View.VISIBLE);
} else {
holder.date.setVisibility(View.GONE);
}
holder.type.setText(log.type.getL10n());
holder.author.setText(StringEscapeUtils.unescapeHtml4(log.author));
// finds count
holder.count.setVisibility(View.VISIBLE);
if (log.found == -1) {
holder.count.setVisibility(View.GONE);
} else {
holder.count.setText(res.getQuantityString(R.plurals.cache_counts, log.found, log.found));
}
// logtext, avoid parsing HTML if not necessary
String logText = log.log;
if (BaseUtils.containsHtml(logText)) {
logText = log.getDisplayText();
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
holder.text.setText(Html.fromHtml(logText, imageCounter, unknownTagsHandler));
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
LogImageLoader loader = new LogImageLoader(holder);
loader.execute(logText);
}
}
else {
holder.text.setText(logText);
}
// images
if (log.hasLogImages()) {
holder.images.setText(log.getImageTitles());
holder.images.setVisibility(View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagesActivity.startActivityLogImages(CacheDetailActivity.this, cache.getGeocode(), new ArrayList<Image>(log.getLogImages()));
}
});
} else {
holder.images.setVisibility(View.GONE);
}
// colored marker
int marker = log.type.markerId;
if (marker != 0) {
holder.statusMarker.setVisibility(View.VISIBLE);
holder.statusMarker.setImageResource(marker);
}
else {
holder.statusMarker.setVisibility(View.GONE);
}
if (null == convertView) {
// if convertView != null then this listeners are already set
holder.author.setOnClickListener(userActionsClickListener);
holder.text.setMovementMethod(LinkMovementMethod.getInstance());
holder.text.setOnClickListener(decryptTextClickListener);
registerForContextMenu(holder.text);
}
return rowView;
}
});
return view;
}
/** Loads the Log Images outside the ui thread. */
private class LogImageLoader extends AsyncTask<String, Progress, Spanned> {
private LogViewHolder holder;
public LogImageLoader(LogViewHolder holder) {
this.holder = holder;
}
@Override
protected Spanned doInBackground(String... logtext) {
return Html.fromHtml(logtext[0], new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null); //, TextView.BufferType.SPANNABLE)
}
@Override
protected void onPostExecute(Spanned result) {
holder.text.setText(result);
}
}
private class LogViewHolder {
final TextView date;
final TextView type;
final TextView author;
final TextView count;
final TextView text;
final TextView images;
final ImageView statusMarker;
public LogViewHolder(View base) {
date = (TextView) base.findViewById(R.id.added);
type = (TextView) base.findViewById(R.id.type);
author = (TextView) base.findViewById(R.id.author);
count = (TextView) base.findViewById(R.id.count);
text = (TextView) base.findViewById(R.id.log);
images = (TextView) base.findViewById(R.id.log_images);
statusMarker = (ImageView) base.findViewById(R.id.log_mark);
}
}
}
private class WaypointsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_waypoints, null);
final LinearLayout waypoints = (LinearLayout) view.findViewById(R.id.waypoints);
// sort waypoints: PP, Sx, FI, OWN
final List<Waypoint> sortedWaypoints = new ArrayList<Waypoint>(cache.getWaypoints());
Collections.sort(sortedWaypoints);
for (final Waypoint wpt : sortedWaypoints) {
final LinearLayout waypointView = (LinearLayout) getLayoutInflater().inflate(R.layout.waypoint_item, null);
// coordinates
if (null != wpt.getCoords()) {
final TextView coordinatesView = (TextView) waypointView.findViewById(R.id.coordinates);
coordinatesView.setOnClickListener(new CoordinatesFormatSwitcher(wpt.getCoords()));
coordinatesView.setText(wpt.getCoords().toString());
coordinatesView.setVisibility(View.VISIBLE);
}
// info
final String waypointInfo = Formatter.formatWaypointInfo(wpt);
if (StringUtils.isNotBlank(waypointInfo)) {
final TextView infoView = (TextView) waypointView.findViewById(R.id.info);
infoView.setText(waypointInfo);
infoView.setVisibility(View.VISIBLE);
}
// title
final TextView nameView = (TextView) waypointView.findViewById(R.id.name);
if (StringUtils.isNotBlank(wpt.getName())) {
nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.getName()));
} else if (null != wpt.getCoords()) {
nameView.setText(wpt.getCoords().toString());
} else {
nameView.setText(res.getString(R.string.waypoint));
}
wpt.setIcon(res, nameView);
// visited
if (wpt.isVisited()) {
TypedValue a = new TypedValue();
getTheme().resolveAttribute(R.attr.text_color_grey, a, true);
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// really should be just a color!
nameView.setTextColor(a.data);
}
}
// note
if (StringUtils.isNotBlank(wpt.getNote())) {
final TextView noteView = (TextView) waypointView.findViewById(R.id.note);
noteView.setVisibility(View.VISIBLE);
if (BaseUtils.containsHtml(wpt.getNote())) {
noteView.setText(Html.fromHtml(wpt.getNote()), TextView.BufferType.SPANNABLE);
}
else {
noteView.setText(wpt.getNote());
}
}
final View wpNavView = waypointView.findViewById(R.id.wpDefaultNavigation);
wpNavView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavigationAppFactory.startDefaultNavigationApplication(1, CacheDetailActivity.this, wpt);
}
});
wpNavView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
NavigationAppFactory.startDefaultNavigationApplication(2, CacheDetailActivity.this, wpt);
return true;
}
});
registerForContextMenu(waypointView);
waypointView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
waypoints.addView(waypointView);
}
final Button addWaypoint = (Button) view.findViewById(R.id.add_waypoint);
addWaypoint.setClickable(true);
addWaypoint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditWaypointActivity.startActivityAddWaypoint(CacheDetailActivity.this, cache);
refreshOnResume = true;
}
});
return view;
}
}
private class InventoryViewCreator extends AbstractCachingPageViewCreator<ListView> {
@Override
public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_inventory, null);
// TODO: fix layout, then switch back to Android-resource and delete copied one
// this copy is modified to respect the text color
view.setAdapter(new ArrayAdapter<Trackable>(CacheDetailActivity.this, R.layout.simple_list_item_1, cache.getInventory()));
view.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object selection = arg0.getItemAtPosition(arg2);
if (selection instanceof Trackable) {
Trackable trackable = (Trackable) selection;
TrackableActivity.startActivity(CacheDetailActivity.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName());
}
}
});
return view;
}
}
private class ImagesViewCreator extends AbstractCachingPageViewCreator<View> {
@Override
public View getDispatchedView() {
if (cache == null) {
return null; // something is really wrong
}
view = getLayoutInflater().inflate(R.layout.caches_images, null);
if (imagesList == null && isCurrentPage(Page.IMAGES)) {
loadCacheImages();
}
return view;
}
}
public static void startActivity(final Context context, final String geocode, final String cacheName) {
final Intent cachesIntent = new Intent(context, CacheDetailActivity.class);
cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cachesIntent);
}
public static void startActivityGuid(final Context context, final String guid, final String cacheName) {
final Intent cacheIntent = new Intent(context, CacheDetailActivity.class);
cacheIntent.putExtra(Intents.EXTRA_GUID, guid);
cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cacheIntent);
}
/**
* A dialog to allow the user to select reseting coordinates local/remote/both.
*/
private AlertDialog createResetCacheCoordinatesDialog(final Geocache cache, final Waypoint wpt) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.waypoint_reset_cache_coords);
String[] items = new String[] { res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords) };
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
dialog.dismiss();
final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1);
new ResetCoordsThread(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog).start();
}
});
return builder.create();
}
private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> {
private boolean remoteFinished = false;
private boolean localFinished = false;
private final ProgressDialog progressDialog;
private final boolean resetRemote;
protected HandlerResetCoordinates(CacheDetailActivity activity, ProgressDialog progressDialog, boolean resetRemote) {
super(activity);
this.progressDialog = progressDialog;
this.resetRemote = resetRemote;
}
@Override
public void handleMessage(Message msg) {
if (msg.what == ResetCoordsThread.LOCAL) {
localFinished = true;
} else {
remoteFinished = true;
}
if (localFinished && (remoteFinished || !resetRemote)) {
progressDialog.dismiss();
final CacheDetailActivity activity = getActivity();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
}
}
private class ResetCoordsThread extends Thread {
private final Geocache cache;
private final Handler handler;
private final boolean local;
private final boolean remote;
private final Waypoint wpt;
private ProgressDialog progress;
public static final int LOCAL = 0;
public static final int ON_WEBSITE = 1;
public ResetCoordsThread(Geocache cache, Handler handler, final Waypoint wpt, boolean local, boolean remote, final ProgressDialog progress) {
this.cache = cache;
this.handler = handler;
this.local = local;
this.remote = remote;
this.wpt = wpt;
this.progress = progress;
}
@Override
public void run() {
if (local) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords));
}
});
cache.setCoords(wpt.getCoords());
cache.setUserModifiedCoords(false);
cache.deleteWaypointForce(wpt);
cgData.saveChangedCache(cache);
handler.sendEmptyMessage(LOCAL);
}
IConnector con = ConnectorFactory.getConnector(cache);
if (remote && con.supportsOwnCoordinates()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website));
}
});
final boolean result = con.deleteModifiedCoordinates(cache);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (result) {
showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website));
} else {
showToast(getString(R.string.waypoint_coordinates_upload_error));
}
handler.sendEmptyMessage(ON_WEBSITE);
notifyDataSetChanged();
}
});
}
}
}
@Override
protected String getTitle(Page page) {
// show number of waypoints directly in waypoint title
if (page == Page.WAYPOINTS) {
final int waypointCount = cache.getWaypoints().size();
return res.getQuantityString(R.plurals.waypoints, waypointCount, waypointCount);
}
return res.getString(page.titleStringId);
}
@Override
protected Pair<List<? extends Page>, Integer> getOrderedPages() {
final ArrayList<Page> pages = new ArrayList<Page>();
pages.add(Page.WAYPOINTS);
pages.add(Page.DETAILS);
final int detailsIndex = pages.size() - 1;
pages.add(Page.DESCRIPTION);
if (!cache.getLogs().isEmpty()) {
pages.add(Page.LOGS);
}
if (CollectionUtils.isNotEmpty(cache.getFriendsLogs())) {
pages.add(Page.LOGSFRIENDS);
}
if (CollectionUtils.isNotEmpty(cache.getInventory())) {
pages.add(Page.INVENTORY);
}
if (CollectionUtils.isNotEmpty(cache.getImages())) {
pages.add(Page.IMAGES);
}
return new ImmutablePair<List<? extends Page>, Integer>(pages, detailsIndex);
}
@Override
protected AbstractViewPagerActivity.PageViewCreator createViewCreator(Page page) {
switch (page) {
case DETAILS:
return new DetailsViewCreator();
case DESCRIPTION:
return new DescriptionViewCreator();
case LOGS:
return new LogsViewCreator(true);
case LOGSFRIENDS:
return new LogsViewCreator(false);
case WAYPOINTS:
return new WaypointsViewCreator();
case INVENTORY:
return new InventoryViewCreator();
case IMAGES:
return new ImagesViewCreator();
default:
throw new IllegalArgumentException();
}
}
static void updateOfflineBox(final View view, final Geocache cache, final Resources res,
final OnClickListener refreshCacheClickListener,
final OnClickListener dropCacheClickListener,
final OnClickListener storeCacheClickListener) {
// offline use
final TextView offlineText = (TextView) view.findViewById(R.id.offline_text);
final Button offlineRefresh = (Button) view.findViewById(R.id.offline_refresh);
final Button offlineStore = (Button) view.findViewById(R.id.offline_store);
if (cache.isOffline()) {
long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes
String ago;
if (diff < 15) {
ago = res.getString(R.string.cache_offline_time_mins_few);
} else if (diff < 50) {
ago = res.getString(R.string.cache_offline_time_about) + " " + diff + " " + res.getString(R.string.cache_offline_time_mins);
} else if (diff < 90) {
ago = res.getString(R.string.cache_offline_time_about) + " " + res.getString(R.string.cache_offline_time_hour);
} else if (diff < (48 * 60)) {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / 60) + " " + res.getString(R.string.cache_offline_time_hours);
} else {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / (24 * 60)) + " " + res.getString(R.string.cache_offline_time_days);
}
offlineText.setText(res.getString(R.string.cache_offline_stored) + "\n" + ago);
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_drop));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(dropCacheClickListener);
} else {
offlineText.setText(res.getString(R.string.cache_offline_not_ready));
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_store));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(storeCacheClickListener);
}
offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE);
offlineRefresh.setClickable(true);
}
}
|