Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d21dea4cd | ||
|
|
e4603a231e | ||
|
|
316df58af6 | ||
|
|
35516af52b | ||
|
|
3bded2af7a | ||
|
|
2c788e3329 | ||
|
|
af2409a16d | ||
|
|
7e390ed56f | ||
|
|
756a816abb | ||
|
|
1e174f77f7 | ||
|
|
ae8e1ddb82 | ||
|
|
9381065cf2 | ||
|
|
98b4ee71ae | ||
|
|
1b84c6fc15 | ||
|
|
ad9fb99205 | ||
|
|
4fdbf10054 | ||
|
|
3505c379cf | ||
|
|
6322022f47 | ||
|
|
adf60f289b | ||
|
|
27ccac205b | ||
|
|
664a7d4cea | ||
|
|
49137e111b | ||
|
|
c834551c52 | ||
|
|
91d5a7be50 | ||
|
|
552c2215c3 | ||
|
|
2e9597f34d | ||
|
|
ec6f25e11b | ||
|
|
f871761e48 | ||
|
|
60bbfceb7e | ||
|
|
0ce1657c0a | ||
|
|
035aebe741 | ||
|
|
a829aa01df | ||
|
|
76315eedc3 | ||
|
|
108df0d614 | ||
|
|
449e128373 | ||
|
|
be53bc8cfa | ||
|
|
70f8c27341 | ||
|
|
f27c43bf92 | ||
|
|
5a9e73b72f | ||
|
|
f2c98815ff | ||
|
|
99abe5e86e | ||
|
|
55a8c55aba | ||
|
|
16c31df0bf | ||
|
|
10feb5d6aa | ||
|
|
f8371a4b0a | ||
|
|
f8ed7dfac4 | ||
|
|
5b0f0bef32 | ||
|
|
c207f5470a | ||
|
|
1002351f2d | ||
|
|
dd4cc41740 | ||
|
|
3f43df52e9 | ||
|
|
de8ad98f8d | ||
|
|
0fc0605a85 | ||
|
|
326e56a24c | ||
|
|
6f388520f5 | ||
|
|
c8a52eec58 | ||
|
|
e568f43dd7 | ||
|
|
22ccdd21ac | ||
|
|
6137fface2 | ||
|
|
4588941a40 | ||
|
|
b943eb2028 | ||
|
|
80e7a3e800 | ||
|
|
51f941f68e | ||
|
|
43a966e81f | ||
|
|
e455bec77b | ||
|
|
a7c4e82050 | ||
|
|
40b2a25633 | ||
|
|
34dccea36f | ||
|
|
0c3188dec0 | ||
|
|
21300cb695 | ||
|
|
5afec93cbf | ||
|
|
482c4cb1e5 | ||
|
|
40794ccc88 | ||
|
|
f27f0d39b0 | ||
|
|
5acfb36369 | ||
|
|
38573fdc85 | ||
|
|
a5ba028d55 | ||
|
|
dfa6288272 | ||
|
|
b62f6510bb | ||
|
|
5d8539282a | ||
|
|
e79315ba9f | ||
|
|
a175a98236 | ||
|
|
1f619a93db | ||
|
|
9f596c4f2c | ||
|
|
e3105027ae | ||
|
|
955230f233 | ||
|
|
c56a601e5c | ||
|
|
107cff1f86 | ||
|
|
89fbc26dd2 | ||
|
|
58e5c45ef0 | ||
|
|
352941098f | ||
|
|
e132e9cd32 | ||
|
|
4e0078846c | ||
|
|
54bd77e090 | ||
|
|
b4b4eec430 | ||
|
|
e338fd6c47 | ||
|
|
66550094c8 | ||
|
|
1e9d00279f | ||
|
|
6bb03cd52a | ||
|
|
dde7331fd4 | ||
|
|
54a4b3ba49 | ||
|
|
fa828ad7ed | ||
|
|
e27823545c | ||
|
|
342df70b38 | ||
|
|
077d4ac9ed | ||
|
|
c56a24b18c | ||
|
|
57ac21c2e8 | ||
|
|
de0bb9e9c6 | ||
|
|
51e728ddfe | ||
|
|
aa8988bd9c | ||
|
|
252ee01ca0 | ||
|
|
1ee872e668 | ||
|
|
5f6f9380e6 | ||
|
|
951c149b6b | ||
|
|
e36909dc06 | ||
|
|
b3f6ff816b | ||
|
|
3ab92847f5 | ||
|
|
6025a0333c | ||
|
|
37877642da | ||
|
|
9ce2f9aa27 | ||
|
|
db788a36eb | ||
|
|
f8339a36f7 | ||
|
|
f26355de41 | ||
|
|
11d8066a07 | ||
|
|
36b5fc7957 | ||
|
|
8aa383a002 | ||
|
|
1d3c8335c7 | ||
|
|
aeee482128 | ||
|
|
6bf3663c81 | ||
|
|
48519aefa5 | ||
|
|
0d05a03f6e | ||
|
|
4bff009cfc | ||
|
|
ba1b5ab29a | ||
|
|
8bfce31f2e | ||
|
|
bca818e734 | ||
|
|
c95015c234 | ||
|
|
3eced06154 | ||
|
|
894b24a4ff | ||
|
|
5a3b0a62f6 | ||
|
|
d34a88943a | ||
|
|
6a611d57d3 | ||
|
|
a3e213eea2 | ||
|
|
9849d7c51e | ||
|
|
e3d0122fb0 | ||
|
|
549c4b559b | ||
|
|
c4b92b734c | ||
|
|
ff763ec44c | ||
|
|
912151ef2d | ||
|
|
f341e8eb10 | ||
|
|
64af6ae5aa | ||
|
|
1d64d0bd23 | ||
|
|
bc19ba5fd0 | ||
|
|
aea6edd08b | ||
|
|
9b62b46e0e | ||
|
|
dcad963c7c | ||
|
|
f66a6e8a49 | ||
|
|
51931b979f | ||
|
|
d863b0927e | ||
|
|
bfaf634148 | ||
|
|
e8760938af | ||
|
|
5bb3275a54 | ||
|
|
d5362ff41d | ||
|
|
949a0d2770 | ||
|
|
8af818ffbe | ||
|
|
ac8b771ecf | ||
|
|
3f25520284 | ||
|
|
2ef558894f | ||
|
|
b68b63a110 | ||
|
|
9f2ec5fb38 | ||
|
|
9564586f97 | ||
|
|
4fdfeec9a5 | ||
|
|
ffb4b56073 | ||
|
|
b0d71102f3 | ||
|
|
c784c85909 | ||
|
|
b977a80ecc | ||
|
|
f3251a4139 | ||
|
|
d5b82cddc8 | ||
|
|
7ad855a4aa | ||
|
|
9826392819 | ||
|
|
9e8a519bc7 | ||
|
|
2029d47b29 | ||
|
|
0622b4cbc5 | ||
|
|
474432d2a7 | ||
|
|
135afc064b | ||
|
|
17006aafe3 | ||
|
|
e5aa030857 | ||
|
|
c8e0a7f16e | ||
|
|
35d8f06e5d | ||
|
|
b967f318c7 | ||
|
|
e1f28ffd23 | ||
|
|
6d5ce170bd | ||
|
|
4d1d87d8ef | ||
|
|
d032e2e577 | ||
|
|
0a7e33503f | ||
|
|
f62c5b41cf | ||
|
|
cdfc018c33 | ||
|
|
9a773ca13f | ||
|
|
1b80e9415f | ||
|
|
706f24f104 | ||
|
|
4029c15eb9 | ||
|
|
6fd3209304 | ||
|
|
ffa3ff7d46 | ||
|
|
83530a9a41 | ||
|
|
7ed7d8cfcf | ||
|
|
aff152543c | ||
|
|
bb92acc66a | ||
|
|
bfad0d8716 | ||
|
|
a8028ff446 | ||
|
|
32bcbf3647 | ||
|
|
52ff3d660c | ||
|
|
e794d83ec5 | ||
|
|
95b82b133a | ||
|
|
a66cc3bb0c | ||
|
|
87abaf05c1 | ||
|
|
3e575f96e6 | ||
|
|
a318d10f79 | ||
|
|
969d59c4c3 | ||
|
|
66ba4e0d09 | ||
|
|
e87199c024 | ||
|
|
7a6b7084ac | ||
|
|
42ed5a03e1 | ||
|
|
8a564df34f | ||
|
|
746faf92b1 | ||
|
|
de74b222af | ||
|
|
66daf0c7b7 | ||
|
|
7e0b4d88d5 | ||
|
|
543b3587eb | ||
|
|
aa6d0cfab5 | ||
|
|
84fd69dfdb | ||
|
|
8c174f8581 | ||
|
|
6bd040272b | ||
|
|
2d2caaed09 | ||
|
|
cf99d87a66 | ||
|
|
778677ec40 | ||
|
|
485f56e547 | ||
|
|
13080b113b | ||
|
|
d1fc3bee96 | ||
|
|
8bd0cf7bc2 | ||
|
|
c306987b63 | ||
|
|
84beb97a73 | ||
|
|
82b7b5544d | ||
|
|
942e42ae76 | ||
|
|
ed8846d950 | ||
|
|
6bd27b2eff | ||
|
|
ef86399ba3 | ||
|
|
6b5f85fe5f | ||
|
|
822f4044f7 | ||
|
|
7414860ace | ||
|
|
582c1c6468 | ||
|
|
192836a763 | ||
|
|
5539048c54 | ||
|
|
61bb009959 | ||
|
|
843b52b468 | ||
|
|
1487957ea4 | ||
|
|
daf517bc6a | ||
|
|
c45b14d35a | ||
|
|
4734c0f7b7 | ||
|
|
0272fb770e | ||
|
|
0b357be701 | ||
|
|
de8a4b8360 | ||
|
|
83dc34fb53 | ||
|
|
8a306727a7 | ||
|
|
3a2eadad70 | ||
|
|
6017db7599 | ||
|
|
bc29648790 | ||
|
|
0ba90a0bb2 | ||
|
|
3ec70113e6 | ||
|
|
0c3b968aee | ||
|
|
b7514953a6 | ||
|
|
0483420af2 | ||
|
|
a72613aa58 | ||
|
|
b45311404c | ||
|
|
df19ff4b14 | ||
|
|
fa6f76ba7d | ||
|
|
5aee1eb084 | ||
|
|
6ef6ab4e67 | ||
|
|
ddf50c4fe1 | ||
|
|
2a8b231e4f | ||
|
|
a8d6643111 | ||
|
|
431b1627df | ||
|
|
f35ba34473 | ||
|
|
284f5d30bb | ||
|
|
72dfb593ce | ||
|
|
7ce521079e | ||
|
|
354776e64a | ||
|
|
21b642fc17 | ||
|
|
8d02c77ad0 | ||
|
|
fdd894c8d0 | ||
|
|
ee46cefeb0 | ||
|
|
eb72336ad0 | ||
|
|
abd400f2cd | ||
|
|
42fc44ce8f | ||
|
|
5205d45f75 | ||
|
|
0cb2413eac | ||
|
|
72ca9ac5dc | ||
|
|
b224c1d2eb | ||
|
|
8fce9a52d8 | ||
|
|
13c6ccd3da | ||
|
|
c9b1b85a57 | ||
|
|
cca2ca819e | ||
|
|
37f701902b | ||
|
|
c8a4c7b081 | ||
|
|
4981deddb9 | ||
|
|
a3dca92976 | ||
|
|
220325f1ed | ||
|
|
124f570e9d | ||
|
|
77a0ec44c6 | ||
|
|
7e93d8bcdd | ||
|
|
e72afae503 | ||
|
|
a83314e997 | ||
|
|
585bfc7635 | ||
|
|
8179510ea8 | ||
|
|
61501c54ba |
+4
-1
@@ -17,7 +17,7 @@ target/
|
||||
.factorypath
|
||||
|
||||
# netbeans
|
||||
nbproject/private/
|
||||
Bnbproject/private/
|
||||
|
||||
# intellij
|
||||
.idea/
|
||||
@@ -52,3 +52,6 @@ Package.resolved
|
||||
#xcode
|
||||
xcuserdata/
|
||||
/temp/
|
||||
|
||||
#tools
|
||||
service-tool/dwd-data/
|
||||
|
||||
@@ -1,485 +0,0 @@
|
||||
<code_scheme name="DefaultIntelliJCodeStyleCST" version="173">
|
||||
<option name="OTHER_INDENT_OPTIONS">
|
||||
<value>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</value>
|
||||
</option>
|
||||
<option name="LINE_SEPARATOR" value="
" />
|
||||
<option name="GENERATE_FINAL_PARAMETERS" value="true" />
|
||||
<option name="RIGHT_MARGIN" value="200" />
|
||||
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
|
||||
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
|
||||
<option name="HTML_INLINE_ELEMENTS" value="a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var" />
|
||||
<AndroidXmlCodeStyleSettings>
|
||||
<option name="USE_CUSTOM_SETTINGS" value="true" />
|
||||
</AndroidXmlCodeStyleSettings>
|
||||
<CssCodeStyleSettings>
|
||||
<option name="HEX_COLOR_LOWER_CASE" value="true" />
|
||||
<option name="HEX_COLOR_LONG_FORMAT" value="true" />
|
||||
</CssCodeStyleSettings>
|
||||
<HTMLCodeStyleSettings>
|
||||
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
|
||||
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
|
||||
<option name="HTML_INLINE_ELEMENTS" value="abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,q,s,samp,span,strike,strong,sub,sup,textarea,tt,u,var" />
|
||||
</HTMLCodeStyleSettings>
|
||||
<JavaeeCodeStyleSettings>
|
||||
<option name="ENTITY_VO_SUFFIX" value="DTO" />
|
||||
</JavaeeCodeStyleSettings>
|
||||
<Objective-C-extensions>
|
||||
<file>
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
|
||||
</file>
|
||||
<class>
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
|
||||
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
|
||||
</class>
|
||||
<extensions>
|
||||
<pair source="cpp" header="hpp" fileNamingConvention="LOWERCASE" />
|
||||
<pair source="c" header="h" fileNamingConvention="NONE" />
|
||||
</extensions>
|
||||
</Objective-C-extensions>
|
||||
<Properties>
|
||||
<option name="KEEP_BLANK_LINES" value="true" />
|
||||
</Properties>
|
||||
<TypeScriptCodeStyleSettings version="0">
|
||||
<option name="FORCE_SEMICOLON_STYLE" value="true" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
|
||||
<option name="OBJECT_LITERAL_WRAP" value="1" />
|
||||
</TypeScriptCodeStyleSettings>
|
||||
<XML>
|
||||
<option name="XML_TEXT_WRAP" value="0" />
|
||||
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
|
||||
</XML>
|
||||
<codeStyleSettings language="CFML">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="CMake">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="CSS">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="CoffeeScript">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="8" />
|
||||
<option name="TAB_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="DB2">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Derby">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="ECMA Script Level 4">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="GSP">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Gherkin">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Groovy">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="H2">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="HAML">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="HSQLDB">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="HTML">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Haml">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JAVA">
|
||||
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
|
||||
<option name="ELSE_ON_NEW_LINE" value="true" />
|
||||
<option name="WHILE_ON_NEW_LINE" value="true" />
|
||||
<option name="CATCH_ON_NEW_LINE" value="true" />
|
||||
<option name="FINALLY_ON_NEW_LINE" value="true" />
|
||||
<option name="ALIGN_MULTILINE_CHAINED_METHODS" value="true" />
|
||||
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
|
||||
<option name="METHOD_CALL_CHAIN_WRAP" value="5" />
|
||||
<option name="WRAP_COMMENTS" value="true" />
|
||||
<option name="ENUM_CONSTANTS_WRAP" value="1" />
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
<arrangement>
|
||||
<groups>
|
||||
<group>
|
||||
<type>GETTERS_AND_SETTERS</type>
|
||||
<order>KEEP</order>
|
||||
</group>
|
||||
<group>
|
||||
<type>OVERRIDDEN_METHODS</type>
|
||||
<order>KEEP</order>
|
||||
</group>
|
||||
<group>
|
||||
<type>DEPENDENT_METHODS</type>
|
||||
<order>DEPTH_FIRST</order>
|
||||
</group>
|
||||
</groups>
|
||||
<rules>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<FIELD>true</FIELD>
|
||||
<FINAL>true</FINAL>
|
||||
<STATIC>true</STATIC>
|
||||
<visibility />
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<FIELD>true</FIELD>
|
||||
<STATIC>true</STATIC>
|
||||
<visibility />
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<FIELD>true</FIELD>
|
||||
<FINAL>true</FINAL>
|
||||
<visibility />
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<FIELD>true</FIELD>
|
||||
<visibility />
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
|
||||
<STATIC>true</STATIC>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<CONSTRUCTOR>true</CONSTRUCTOR>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<METHOD>true</METHOD>
|
||||
<NAME>main</NAME>
|
||||
<PUBLIC>true</PUBLIC>
|
||||
<STATIC>true</STATIC>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<ABSTRACT>true</ABSTRACT>
|
||||
<METHOD>true</METHOD>
|
||||
<visibility />
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<ABSTRACT>false</ABSTRACT>
|
||||
<METHOD>true</METHOD>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<METHOD>true</METHOD>
|
||||
<STATIC>true</STATIC>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<ENUM>true</ENUM>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<INTERFACE>true</INTERFACE>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<CLASS>true</CLASS>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<CLASS>true</CLASS>
|
||||
<STATIC>true</STATIC>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
</rules>
|
||||
</arrangement>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JSON">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JSP">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JSPX">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JavaScript">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="LESS">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="MySQL">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="ObjectiveC">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Oracle">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="PostgreSQL">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Puppet">
|
||||
<indentOptions>
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="RHTML">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="8" />
|
||||
<option name="TAB_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="SASS">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="SCSS">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="SQL">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="SQLite">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Stylus">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Sybase">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="TSQL">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="TypeScript">
|
||||
<option name="ELSE_ON_NEW_LINE" value="true" />
|
||||
<option name="CATCH_ON_NEW_LINE" value="true" />
|
||||
<option name="FINALLY_ON_NEW_LINE" value="true" />
|
||||
<option name="TERNARY_OPERATION_WRAP" value="1" />
|
||||
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
|
||||
<option name="IF_BRACE_FORCE" value="1" />
|
||||
<option name="DOWHILE_BRACE_FORCE" value="1" />
|
||||
<option name="WHILE_BRACE_FORCE" value="1" />
|
||||
<option name="FOR_BRACE_FORCE" value="1" />
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="XML">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="kotlin">
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="ruby">
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="4" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="8" />
|
||||
<option name="TAB_SIZE" value="4" />
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
Vendored
+28
-32
@@ -3,17 +3,10 @@
|
||||
// this groovy script is executed by jenkins
|
||||
node {
|
||||
|
||||
|
||||
def gradleInfo
|
||||
def server = Artifactory.server 'project.nes.uni-due.de'
|
||||
def gradleBuild = Artifactory.newGradleBuild()
|
||||
gradleBuild.usesPlugin = true
|
||||
gradleBuild.useWrapper = true
|
||||
|
||||
environment {
|
||||
ANDROID_SDK_ROOT = '/var/lib/android-sdk'
|
||||
}
|
||||
|
||||
// set environment variables
|
||||
env.ANDROID_SDK_ROOT = '/var/lib/android-sdk'
|
||||
env.JAVA_HOME = '/opt/openjdk-bin-11'
|
||||
env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}"
|
||||
|
||||
// checkout code from scm
|
||||
stage('Checkout') {
|
||||
@@ -21,47 +14,50 @@ node {
|
||||
}
|
||||
|
||||
def version = ''
|
||||
def release = false;
|
||||
|
||||
// configure the deployer based on the version
|
||||
stage('Configure') {
|
||||
version = sh(returnStdout: true, script: "./gradlew properties -q | grep \"version:\" | awk '{print \$2}'", label: "Detecting project version.").trim()
|
||||
println "Version is: '${version}'"
|
||||
if (version.endsWith("-SNAPSHOT")) {
|
||||
println "Using internal-snapshots for publication."
|
||||
gradleBuild.deployer server: server, repo: 'internal-snapshots'
|
||||
} else {
|
||||
println "Using internal-releases for publication."
|
||||
gradleBuild.deployer server: server, repo: 'internal-releases'
|
||||
}
|
||||
println "Version is: '${version}'"
|
||||
release = (! version.endsWith("-SNAPSHOT"))
|
||||
}
|
||||
|
||||
// build the source code with gradle
|
||||
stage('Build') {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
|
||||
gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'clean build', switches: switches
|
||||
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD clean build', label: "Building project.")
|
||||
}
|
||||
}
|
||||
|
||||
// deploy the maven publications to artifactory
|
||||
// deploy the maven publications to nexus
|
||||
stage ('Publish') {
|
||||
if (env.BRANCH_NAME == "master") {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
|
||||
gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'artifactoryPublish', switches: switches
|
||||
}
|
||||
withCredentials([string(credentialsId: 'jenkins-nexus-password', variable: 'NEXUS')]) {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD -Djenkins.nexus.password=$NEXUS publishAllPublicationsToMavenRepository', label: "Publishing project.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
echo "Skipping deployment for non-master branch."
|
||||
echo "Skipping publication for non-release version or non-master branch."
|
||||
}
|
||||
}
|
||||
|
||||
// deploy the build output on the server
|
||||
stage ('Deploy') {
|
||||
if (env.BRANCH_NAME == "master") {
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "keyfile")]) {
|
||||
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@apps.nes.uni-due.de:/opt/wildfly-17-mowesta/standalone/deployments/mowesta.ear"
|
||||
sh "scp -i ${keyfile} android-app/build/outputs/apk/release/*.apk wildfly@apps.nes.uni-due.de:/opt/android/mowesta/"
|
||||
}
|
||||
// release = true; // uncomment to temporary enable snapshot deployments
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
echo "Deploying to production server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
// sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
|
||||
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
|
||||
sh 'scp -i $KEYFILE android-app/build/outputs/bundle/prodRelease/*.aab wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
|
||||
}
|
||||
} else if (env.BRANCH_NAME == "master") {
|
||||
/* echo "Deploying to beta server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
|
||||
} */
|
||||
} else {
|
||||
echo "Skipping deployment for non-master branch."
|
||||
}
|
||||
|
||||
@@ -13,3 +13,4 @@ To build the project, you will have to install [Java](http://www.oracle.com/tech
|
||||
# Jenkins CI
|
||||
|
||||
Pull requests and new commits to any branch are automatically built by a Jenkins service. A Gitea webhook informs the service about changes to the repository. In addition, the service will automatically scan the lbs Gitea organization for new repositories every hour. Successful builds of new commits are indicated by a green tick on the commit page. The build status of pull requests is currently not shown in Gitea. However, you can go to the [Jenkins](https://project.nes.uni-due.de/jenkins/job/LocationBasedServices/job/mowesta/) service to view the result of builds including the console output. To modify the build process, you can change the Jenkinsfile groovy script in the root of the repository, if necessary.
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
plugins {
|
||||
id 'org.hidetake.swagger.generator' version '2.18.2'
|
||||
}
|
||||
|
||||
description = "MoWeSta Android Api"
|
||||
|
||||
// downgrade jackson for Android, since versions > 2.9
|
||||
// will contain module-info.class files that will result
|
||||
// in a large number of android lint warnings
|
||||
versionJackson = "2.9.10"
|
||||
|
||||
dependencies {
|
||||
api "de.grundid.opendatalab:geojson-jackson:${versionGeojson}"
|
||||
api "io.swagger:swagger-annotations:${versionSwagger}"
|
||||
api "com.fasterxml.jackson.core:jackson-core:${versionJackson}"
|
||||
api "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
|
||||
api "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
api "com.fasterxml.jackson.datatype:jackson-datatype-joda:${versionJackson}"
|
||||
api "javax.annotation:javax.annotation-api:${versionAnnotation}"
|
||||
api "io.github.openfeign:feign-core:9.4.0"
|
||||
api "io.github.openfeign:feign-jackson:9.4.0"
|
||||
compileOnly "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.1"
|
||||
swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.9'
|
||||
}
|
||||
|
||||
sourceSets.main.java.srcDirs = ['src/main/java', 'build/swagger/src/main/java']
|
||||
|
||||
swaggerSources {
|
||||
mowesta {
|
||||
inputFile = file(project(':common-api:').buildDir.path + '/swagger/mowesta.json')
|
||||
code {
|
||||
outputDir = file("${project.buildDir}/swagger")
|
||||
language = 'java'
|
||||
configFile = file('config.json')
|
||||
components = [ models: true, apis: 'Default']
|
||||
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// require api build to access swagger definition
|
||||
tasks['resolveSwaggerTemplate'].dependsOn(project(':common-api').tasks['build'])
|
||||
// require swagger code gen before compilation
|
||||
compileJava.dependsOn('generateSwaggerCode')
|
||||
+3
@@ -40,6 +40,9 @@ public class ApiClient {
|
||||
})
|
||||
.encoder(new JacksonEncoder(objectMapper))
|
||||
.decoder(new JacksonDecoder(objectMapper));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public ApiClient(String[] authNames) {
|
||||
+64
-36
@@ -2,36 +2,47 @@ apply plugin: 'org.handte.gradle-android-eclipse'
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
|
||||
|
||||
description = "Mowesta Android App"
|
||||
description = "MoWeSta Android App"
|
||||
|
||||
|
||||
ext {
|
||||
// android app dependencies
|
||||
versionPlay = '17.0.0'
|
||||
versionAndroidXCore = '1.2.0'
|
||||
versionAndroidXCore = '1.3.1'
|
||||
versionAndroidXCoreTest = '2.1.0'
|
||||
versionAndroidXRecycler = '1.1.0'
|
||||
versionAndroidXRecycler = '1.2.1'
|
||||
versionAndroidXPaging = '2.1.2'
|
||||
versionAndroidXCard = '1.0.0'
|
||||
versionAndroidXCoordinator = '1.1.0'
|
||||
versionAndroidXConstraint = '1.1.3'
|
||||
versionAndroidXNavigation = '2.3.0-beta01'
|
||||
versionAndroidXLifecycle = '2.2.0'
|
||||
versionAndroidXSecurity = '1.0.0-rc02'
|
||||
versionAndroidXCoordinator = '1.2.0'
|
||||
versionAndroidXConstraint = '2.1.4'
|
||||
versionAndroidXNavigation = '2.5.3'
|
||||
versionAndroidXLifecycle = '2.5.1'
|
||||
versionAndroidXSecurity = '1.0.0'
|
||||
versionAndroidXViewpager = '1.0.0'
|
||||
versionGoogleMaterial = '1.1.0'
|
||||
versionAndroidXSwipeRefresh = '1.0.0'
|
||||
versionExoPlayer = '2.11.5'
|
||||
versionAndroidXWork = '2.7.1'
|
||||
versionGoogleMaterial = '1.7.0'
|
||||
versionAndroidXSwipeRefresh = '1.1.0'
|
||||
versionAndroidXWebkit = '1.5.0'
|
||||
versionExoPlayer = '2.18.1'
|
||||
versionApp = project.version
|
||||
}
|
||||
|
||||
// remove project version to workaround bugs in
|
||||
// oss-license-plugin that detects local libraries
|
||||
// by checking for a version called "unspecified"
|
||||
// see DependencyTask.groovy on GitHub at
|
||||
// https://github.com/google/play-services-plugins
|
||||
project.version = "unspecified"
|
||||
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(dir: "libs", include: ["*.jar"])
|
||||
implementation project(":android-sdk")
|
||||
|
||||
implementation "javax.xml.bind:jaxb-api:${versionJaxb}"
|
||||
|
||||
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
|
||||
|
||||
implementation "androidx.work:work-runtime:${versionAndroidXWork}"
|
||||
implementation "com.google.android.material:material:${versionGoogleMaterial}"
|
||||
implementation "androidx.preference:preference:${versionAndroidXPreference}"
|
||||
implementation "androidx.cardview:cardview:${versionAndroidXCard}"
|
||||
@@ -51,6 +62,7 @@ dependencies {
|
||||
implementation "androidx.lifecycle:lifecycle-service:${versionAndroidXLifecycle}"
|
||||
implementation "androidx.lifecycle:lifecycle-process:${versionAndroidXLifecycle}"
|
||||
|
||||
implementation "androidx.webkit:webkit:${versionAndroidXWebkit}"
|
||||
|
||||
implementation "com.google.android.exoplayer:exoplayer-core:${versionExoPlayer}"
|
||||
implementation "com.google.android.exoplayer:exoplayer-ui:${versionExoPlayer}"
|
||||
@@ -72,24 +84,24 @@ dependencies {
|
||||
testImplementation "junit:junit:${versionJunit}"
|
||||
testImplementation "androidx.test:core:${versionAndroidXTest}"
|
||||
testImplementation "androidx.arch.core:core-testing:${versionAndroidXCoreTest}"
|
||||
testImplementation "org.robolectric:robolectric:${versionRobolectric}"
|
||||
|
||||
}
|
||||
|
||||
configurations {
|
||||
all {
|
||||
exclude group: 'com.google.auto.service', module: 'auto-service'
|
||||
}
|
||||
all {
|
||||
exclude group: 'com.google.auto.service', module: 'auto-service'
|
||||
exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel-ktx'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
compileSdkVersion 33
|
||||
defaultConfig {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 29
|
||||
versionCode 5
|
||||
versionName "${version}"
|
||||
targetSdkVersion 33
|
||||
versionCode 29
|
||||
versionName "${versionApp}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
resValue "string", "application_long", "MoWeSta"
|
||||
@@ -97,6 +109,11 @@ android {
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
}
|
||||
javaCompileOptions {
|
||||
annotationProcessorOptions {
|
||||
arguments += ["room.schemaLocation": "${projectDir}/src/main/sql/".toString()]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -119,7 +136,20 @@ android {
|
||||
debug {
|
||||
applicationIdSuffix ".debug"
|
||||
versionNameSuffix "-dbg"
|
||||
resValue "string", "application_long", "MoWeSta (Debug)"
|
||||
}
|
||||
}
|
||||
flavorDimensions "backend"
|
||||
productFlavors {
|
||||
beta {
|
||||
dimension "backend"
|
||||
applicationIdSuffix ".beta"
|
||||
resValue "string", "mowesta_url_default", "https://www.mowesta.com/api"
|
||||
// resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
|
||||
resValue "string", "application_long", "B-MoWeSta"
|
||||
}
|
||||
prod {
|
||||
dimension "backend"
|
||||
resValue "string", "mowesta_url_default", "https://www.mowesta.com/api"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,24 +162,19 @@ android {
|
||||
includeAndroidResources = true
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
// FragmentTagUsage: replacing fragment with FragmentContainerView breaks Navigation library
|
||||
// RelativeOverlayp: occurs in video frame which is what we want
|
||||
// VectorPath: our map and logo representations are very long vectors (consider compressing)
|
||||
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
|
||||
abortOnError false
|
||||
}
|
||||
|
||||
dexOptions {
|
||||
javaMaxHeapSize "512m"
|
||||
}
|
||||
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
lint {
|
||||
abortOnError false
|
||||
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
|
||||
}
|
||||
namespace 'com.mowesta.android.app'
|
||||
|
||||
}
|
||||
|
||||
// enable unchecked and deprecation warning during compilation
|
||||
gradle.projectsEvaluated {
|
||||
@@ -174,4 +199,7 @@ eclipse {
|
||||
}
|
||||
}
|
||||
|
||||
if (System.properties['android.keystore.password'] != null) {
|
||||
build.dependsOn "bundle"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="com.mowesta.android.app">
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
|
||||
@@ -28,21 +29,57 @@
|
||||
android:supportsRtl="true"
|
||||
android:fullBackupContent="@xml/backup">
|
||||
<activity
|
||||
android:launchMode="singleTask"
|
||||
android:launchMode="singleTop"
|
||||
android:name=".MowestaActivity"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:exported="true"
|
||||
android:label="@string/application_long">
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<receiver android:name=".MowestaReceiver">
|
||||
<activity
|
||||
android:name=".widget.ForecastWidgetActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".widget.MeasureWidgetActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<receiver android:name=".MowestaReceiver" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED"/>
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<service android:name=".MowestaService" />
|
||||
<receiver
|
||||
android:name=".widget.ForecastWidgetProvider"
|
||||
android:exported="true"
|
||||
android:label="@string/widget_forecast_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider"
|
||||
android:resource="@xml/widget_forecast" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:exported="true"
|
||||
android:name=".widget.MeasureWidgetProvider"
|
||||
android:label="@string/widget_measure_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider"
|
||||
android:resource="@xml/widget_measure" />
|
||||
</receiver>
|
||||
<service android:name=".MowestaService" android:exported="true"/>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
Binary file not shown.
@@ -7,6 +7,7 @@ import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.repository.DeviceRepository;
|
||||
import com.mowesta.android.app.repository.FavoriteRepository;
|
||||
import com.mowesta.android.app.repository.UserRepository;
|
||||
import com.mowesta.android.app.repository.WidgetRepository;
|
||||
|
||||
/**
|
||||
* An interface for the application context used
|
||||
@@ -44,6 +45,13 @@ public interface IApp {
|
||||
*/
|
||||
FavoriteRepository getFavoriteRepository();
|
||||
|
||||
/**
|
||||
* Returns a reference to the widget repository.
|
||||
*
|
||||
* @return The widget repository.
|
||||
*/
|
||||
WidgetRepository getWidgetRepository();
|
||||
|
||||
/**
|
||||
* Returns a reference to the http client factory.
|
||||
*
|
||||
@@ -58,4 +66,11 @@ public interface IApp {
|
||||
*/
|
||||
Cache getMediaCache();
|
||||
|
||||
/**
|
||||
* Returns a settings instance.
|
||||
*
|
||||
* @return The settings instance.
|
||||
*/
|
||||
MowestaSettings getSettings();
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.mowesta.android.app;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
|
||||
import android.content.pm.PackageManager;
|
||||
@@ -7,30 +11,34 @@ import android.net.Uri;
|
||||
import android.net.http.HttpResponseCache;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.PersistableBundle;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
import android.Manifest;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.PermissionChecker;
|
||||
import androidx.navigation.NavDeepLinkBuilder;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.navigation.NavBackStackEntry;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavDirections;
|
||||
import androidx.navigation.NavOptionsBuilder;
|
||||
import androidx.navigation.Navigation;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.google.android.material.snackbar.BaseTransientBottomBar;
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.generated.callback.OnClickListener;
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.task.RefreshTask;
|
||||
import com.mowesta.android.app.task.SyncTask;
|
||||
import com.mowesta.android.app.util.PermissionUtil;
|
||||
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.sdk.SdkRepository;
|
||||
import com.mowesta.android.sdk.task.ClearTask;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -52,12 +60,22 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
/**
|
||||
* One hour in milliseconds.
|
||||
*/
|
||||
private static final int ONE_HOUR = 60*60*1000;
|
||||
private static final int DELAY_REFRESH = 15 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The code used to request the permissions.
|
||||
* Requests the permission to issue notifications.
|
||||
*/
|
||||
private static final int CODE_REQUEST_PERMISSIONS = 3334;
|
||||
public static final int CODE_REQUEST_POST_NOTIFICATION = 3333;
|
||||
/**
|
||||
* The code used to request the permission for localizing in the foreground.
|
||||
*/
|
||||
public static final int CODE_REQUEST_FOREGROUND_PERMISSIONS = 3334;
|
||||
|
||||
/**
|
||||
* The code used to request the permission for localizing in the background.
|
||||
*/
|
||||
private static final int CODE_REQUEST_BACKGROUND_PERMISSIONS = 3335;
|
||||
|
||||
|
||||
/**
|
||||
* The preferences.
|
||||
@@ -76,12 +94,18 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
protected DatabaseTask<FavoriteDatabase, Void, Long> favoriteTask = new DatabaseTask<>(
|
||||
(input, database) -> database.getAccessor().getUpdateTime(),
|
||||
(input, result) -> {
|
||||
if (result != null && result < System.currentTimeMillis() - ONE_HOUR) {
|
||||
FavoriteDatabase db = app.getFavoriteRepository().getDatabase();
|
||||
if (result != null && result < System.currentTimeMillis() - DELAY_REFRESH) {
|
||||
Log.d(TAG, "Starting automatic favorite synchronization.");
|
||||
UserCredentials c = app.getUserRepository().getCredentials().getValue();
|
||||
FavoriteDatabase db = app.getFavoriteRepository().getDatabase();
|
||||
if (c != null) new SyncTask(db, null).execute(app.getClientFactory().createClient(c));
|
||||
new RefreshTask(db, null).execute(app.getClientFactory().createClient());
|
||||
DefaultApi client = app.getClientFactory().createClient(c);
|
||||
if (c != null) {
|
||||
new SyncTask(db, (success)-> {
|
||||
new RefreshTask(db, null).execute(client);
|
||||
}).execute(client);
|
||||
} else {
|
||||
new RefreshTask(db, null).execute(app.getClientFactory().createClient());
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Ignoring request for favorite synchronization since data is up-to-date.");
|
||||
}
|
||||
@@ -97,7 +121,9 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
private OnSharedPreferenceChangeListener preferenceListener = (prefs, key) -> {
|
||||
if (MowestaSettings.PRIVACY_MEASURE.equals(key)) {
|
||||
if (settings.isPrivacyMeasure()) {
|
||||
if (!PermissionUtil.hasPermissions(this)) requestPermissions();
|
||||
if (!PermissionUtil.hasBackgroundPermissions(this) ||
|
||||
!PermissionUtil.hasNotificationPermission(this))
|
||||
requestPermissions(false);
|
||||
else MowestaService.startService(this);
|
||||
} else {
|
||||
MowestaService.stopService(this);
|
||||
@@ -105,29 +131,63 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
}
|
||||
};
|
||||
|
||||
public MowestaActivity() {
|
||||
super(R.layout.activity_app);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
app = (IApp) getApplication();
|
||||
favoriteTask.execute(null, app.getFavoriteRepository().getDatabase());
|
||||
settings = new MowestaSettings(getApplication());
|
||||
setContentView(R.layout.activity_app);
|
||||
settings = app.getSettings();
|
||||
installHttpCache();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
// got to navigation drawer when user presses notification
|
||||
setIntent(intent);
|
||||
Navigation.findNavController(this, R.id.navigation_app).navigate(R.id.action_drawer);
|
||||
}
|
||||
|
||||
// got to navigation drawer when user presses notification
|
||||
private void handleNotificationIntent() {
|
||||
Intent intent = getIntent();
|
||||
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
|
||||
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
|
||||
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
|
||||
NavController controller = Navigation.findNavController(this, R.id.navigation_app);
|
||||
if (controller.getGraph().getId() == R.id.navigation_core) {
|
||||
controller.navigate(R.id.action_drawer);
|
||||
} else {
|
||||
boolean hasDrawer = false;
|
||||
for (NavBackStackEntry entry: controller.getBackQueue()) {
|
||||
if (entry.getDestination().getId() == R.id.destination_drawer) {
|
||||
hasDrawer = true;
|
||||
}
|
||||
}
|
||||
if (hasDrawer) {
|
||||
controller.navigate(R.id.action_drawer);
|
||||
} else {
|
||||
controller.navigate(R.id.action_core);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
settings.getPreferences().registerOnSharedPreferenceChangeListener(preferenceListener);
|
||||
handleNotificationIntent();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostResume() {
|
||||
super.onPostResume();
|
||||
MowestaService.startService(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -170,9 +230,15 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
/**
|
||||
* Method to request location permission for the app.
|
||||
*/
|
||||
private void requestPermissions() {
|
||||
public void requestPermissions(boolean skipNotification) {
|
||||
Log.d(TAG, "Requesting permissions.");
|
||||
ActivityCompat.requestPermissions(this, PermissionUtil.getNonGrantedPermissions(this), CODE_REQUEST_PERMISSIONS);
|
||||
if (!skipNotification && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !PermissionUtil.hasNotificationPermission(this)) {
|
||||
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, CODE_REQUEST_POST_NOTIFICATION);
|
||||
} else if (!PermissionUtil.hasPermissions(this, PermissionUtil.getForegroundPermissions(this))) {
|
||||
ActivityCompat.requestPermissions(this, PermissionUtil.getForegroundPermissions(this), CODE_REQUEST_BACKGROUND_PERMISSIONS);
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
|
||||
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION }, CODE_REQUEST_BACKGROUND_PERMISSIONS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,8 +250,16 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
*/
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
switch (requestCode) {
|
||||
case CODE_REQUEST_PERMISSIONS: {
|
||||
case CODE_REQUEST_POST_NOTIFICATION: {
|
||||
if (!PermissionUtil.hasBackgroundPermissions(this))
|
||||
requestPermissions(true);
|
||||
else MowestaService.startService(this);
|
||||
break;
|
||||
}
|
||||
case CODE_REQUEST_BACKGROUND_PERMISSIONS:
|
||||
case CODE_REQUEST_FOREGROUND_PERMISSIONS: {
|
||||
boolean granted = true;
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (int i = 0, s = Math.min(permissions.length, grantResults.length); i < s; i++) {
|
||||
@@ -196,23 +270,11 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
Log.d(TAG, "Permission result: " + b.toString());
|
||||
if (!granted) {
|
||||
settings.setPrivacyMeasure(false);
|
||||
View coordinator = findViewById(R.id.layout_coordinator);
|
||||
Snackbar.make(coordinator, R.string.message_no_permission, Snackbar.LENGTH_LONG )
|
||||
.setAction(R.string.button_configure, (view) -> {
|
||||
// go to app settings
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
Uri uri = Uri.fromParts("package", getPackageName(), null);
|
||||
intent.setData(uri);
|
||||
try {
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
Snackbar.make(coordinator, R.string.message_configure_failed,
|
||||
Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
}).show();
|
||||
showMissingPermission(requestCode == CODE_REQUEST_FOREGROUND_PERMISSIONS);
|
||||
} else {
|
||||
MowestaService.startService(this);
|
||||
if (!PermissionUtil.hasBackgroundPermissions(this))
|
||||
settings.setPrivacyMeasure(false);
|
||||
else MowestaService.startService(this);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -221,4 +283,62 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a snackbar indicating a missing permission.
|
||||
*/
|
||||
public void showMissingPermission(boolean foreground) {
|
||||
PermissionDialogFragment pdf = PermissionDialogFragment.newInstance(foreground);
|
||||
pdf.show(getSupportFragmentManager(), "permissions");
|
||||
}
|
||||
|
||||
/**
|
||||
* A dialog fragment to explain the need for permissions.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class PermissionDialogFragment extends DialogFragment {
|
||||
|
||||
private static final String KEY_FOREGROUND = "foreground";
|
||||
|
||||
public static PermissionDialogFragment newInstance(boolean foreground) {
|
||||
PermissionDialogFragment f = new PermissionDialogFragment();
|
||||
Bundle b = new Bundle();
|
||||
b.putBoolean(KEY_FOREGROUND, foreground);
|
||||
f.setArguments(b);
|
||||
return f;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
MaterialAlertDialogBuilder b = new MaterialAlertDialogBuilder(getActivity());
|
||||
b.setTitle(R.string.message_permission_title);
|
||||
b.setMessage(isForeground()?R.string.message_permission_foreground:R.string.message_permission_background);
|
||||
b.setIcon(R.drawable.ic_gps_off_normal_24);
|
||||
b.setNeutralButton(R.string.button_configure, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
|
||||
intent.setData(uri);
|
||||
try {
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
View coordinator = getActivity().findViewById(R.id.layout_coordinator);
|
||||
Snackbar.make(coordinator, R.string.message_configure_failed,
|
||||
Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
});
|
||||
return b.show();
|
||||
}
|
||||
|
||||
private boolean isForeground() {
|
||||
Bundle b = getArguments();
|
||||
return b.getBoolean(KEY_FOREGROUND, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,9 +3,16 @@ package com.mowesta.android.app;
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.res.Configuration;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.StrictMode;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
|
||||
import com.google.android.exoplayer2.database.StandaloneDatabaseProvider;
|
||||
import com.google.android.exoplayer2.upstream.cache.Cache;
|
||||
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
|
||||
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
|
||||
@@ -13,6 +20,11 @@ import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.repository.DeviceRepository;
|
||||
import com.mowesta.android.app.repository.FavoriteRepository;
|
||||
import com.mowesta.android.app.repository.UserRepository;
|
||||
import com.mowesta.android.app.repository.WidgetRepository;
|
||||
import com.mowesta.android.app.widget.AbstractWidgetProvider;
|
||||
import com.mowesta.android.app.widget.ForecastWidgetProvider;
|
||||
import com.mowesta.android.app.widget.MeasureWidgetProvider;
|
||||
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@@ -24,6 +36,16 @@ import java.io.File;
|
||||
*/
|
||||
public class MowestaApp extends Application implements IApp {
|
||||
|
||||
/** The log tag. */
|
||||
public static final String TAG = "MowestaApp";
|
||||
|
||||
/**
|
||||
* The widget providers of the app.
|
||||
*/
|
||||
private AbstractWidgetProvider[] widgetProviders = {
|
||||
new ForecastWidgetProvider(),
|
||||
new MeasureWidgetProvider()
|
||||
};
|
||||
|
||||
/**
|
||||
* The user repository.
|
||||
@@ -40,6 +62,16 @@ public class MowestaApp extends Application implements IApp {
|
||||
*/
|
||||
protected FavoriteRepository favoriteRepository;
|
||||
|
||||
/**
|
||||
* The database for the widgets.
|
||||
*/
|
||||
protected WidgetRepository widgetRepository;
|
||||
|
||||
/**
|
||||
* The application settings.
|
||||
*/
|
||||
protected MowestaSettings settings;
|
||||
|
||||
/**
|
||||
* The cache to store videos.
|
||||
*/
|
||||
@@ -49,12 +81,25 @@ public class MowestaApp extends Application implements IApp {
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
settings = new MowestaSettings(this);
|
||||
userRepository = new UserRepository.Builder().setTrace(false).build(this);
|
||||
deviceRepository = new DeviceRepository.Builder().setTrace(false).build(this);
|
||||
favoriteRepository = new FavoriteRepository(this);
|
||||
MowestaService.startService(this);
|
||||
widgetRepository = new WidgetRepository(this);
|
||||
PeriodicWidgetWorker.updateWidgets(this);
|
||||
PeriodicWidgetWorker.scheduleUpdates(this);
|
||||
//if(BuildConfig.DEBUG)
|
||||
// StrictMode.enableDefaults();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(@NonNull Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
Log.d(TAG, "Configuration change detected.");
|
||||
for (int i = widgetProviders.length - 1; i >= 0; i--) {
|
||||
widgetProviders[i].triggerUpdates(MowestaApp.this, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Context getContext() {
|
||||
@@ -74,6 +119,9 @@ public class MowestaApp extends Application implements IApp {
|
||||
@Override
|
||||
public FavoriteRepository getFavoriteRepository() { return favoriteRepository; }
|
||||
|
||||
@Override
|
||||
public WidgetRepository getWidgetRepository() { return widgetRepository; }
|
||||
|
||||
@Override
|
||||
public ClientFactory getClientFactory() {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
|
||||
@@ -92,9 +140,14 @@ public class MowestaApp extends Application implements IApp {
|
||||
if (mediaCache == null) {
|
||||
mediaCache = new SimpleCache(new File(this.getCacheDir(), "videos"),
|
||||
new LeastRecentlyUsedCacheEvictor(25 * 1000 * 1000),
|
||||
new ExoDatabaseProvider(getContext()));
|
||||
new StandaloneDatabaseProvider(getContext()));
|
||||
}
|
||||
return mediaCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MowestaSettings getSettings() {
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import android.content.Intent;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* A broadcast receiver that registers the background activites at
|
||||
* device boot time.
|
||||
* A broadcast receiver that starts the background service after
|
||||
* a reboot and when the package is updated.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@@ -24,7 +24,8 @@ public class MowestaReceiver extends BroadcastReceiver {
|
||||
// should not happen but nobody likes crashing apps in background
|
||||
if (intent == null || context == null) return;
|
||||
Log.d(TAG, "Received an intent with action " + intent.getAction() + ".");
|
||||
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
|
||||
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ||
|
||||
Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) {
|
||||
MowestaService.startService(context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package com.mowesta.android.app;
|
||||
|
||||
import android.app.Application;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
@@ -9,7 +7,6 @@ import android.os.Build;
|
||||
import com.mowesta.android.app.util.PermissionUtil;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.sdk.SdkService;
|
||||
import com.mowesta.android.sdk.util.CapabilityManager;
|
||||
|
||||
/**
|
||||
* A service to perform background measurements.
|
||||
@@ -21,7 +18,7 @@ public class MowestaService extends SdkService {
|
||||
@Override
|
||||
protected boolean isEnabled() {
|
||||
IApp app = (IApp)getApplication();
|
||||
MowestaSettings settings = new MowestaSettings(getApplication());
|
||||
MowestaSettings settings = app.getSettings();
|
||||
return settings.isPrivacyMeasure() && app.getDeviceRepository().getHandle().getValue() != null;
|
||||
}
|
||||
|
||||
@@ -38,9 +35,9 @@ public class MowestaService extends SdkService {
|
||||
* @param context A context object.
|
||||
*/
|
||||
public static void startService(Context context) {
|
||||
if (!PermissionUtil.hasPermissions(context)) return;
|
||||
if (!PermissionUtil.hasBackgroundPermissions(context)) return;
|
||||
IApp app = (IApp)context.getApplicationContext();
|
||||
MowestaSettings settings = new MowestaSettings((Application)context.getApplicationContext());
|
||||
MowestaSettings settings = app.getSettings();
|
||||
if (!settings.isPrivacyMeasure() || app.getDeviceRepository().getHandle().getValue() == null) return;
|
||||
Intent intent = new Intent();
|
||||
intent.setClass(context, MowestaService.class);
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.content.res.Resources;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.preference.Preference;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.mowesta.android.sdk.SdkSettings;
|
||||
@@ -16,6 +17,22 @@ import com.mowesta.android.sdk.SdkSettings;
|
||||
*/
|
||||
public class MowestaSettings extends SdkSettings {
|
||||
|
||||
/**
|
||||
* An enumeration with the unit system used throughout
|
||||
* the application.
|
||||
*/
|
||||
public enum UnitSystem {
|
||||
BOTH, STANDARD, IMPERIAL
|
||||
}
|
||||
|
||||
/**
|
||||
* An enumeration with the temperature unit to
|
||||
* use throughout the application.
|
||||
*/
|
||||
public enum TemperatureUnit {
|
||||
BOTH, CELSIUS, FAHRENHEIT
|
||||
}
|
||||
|
||||
/**
|
||||
* The key to an integer to store the current version of the terms that the user has accepted.
|
||||
*/
|
||||
@@ -36,12 +53,6 @@ public class MowestaSettings extends SdkSettings {
|
||||
*/
|
||||
public static final String COLLECTION_SHOWN = "collection_shown";
|
||||
|
||||
/**
|
||||
* The key to a boolean to store whether the diagram will use
|
||||
* celsius (true) or fahrenheit (false).
|
||||
*/
|
||||
public static final String TEMPERATURE_CELSIUS = "temperature_celsius";
|
||||
|
||||
/**
|
||||
* The key to a boolean to show/hide the precipitation.
|
||||
*/
|
||||
@@ -72,6 +83,21 @@ public class MowestaSettings extends SdkSettings {
|
||||
*/
|
||||
public static final String SHOW_PRESSURE = "show_pressure";
|
||||
|
||||
/**
|
||||
* The key to a boolean to show/hide the scale on videos.
|
||||
*/
|
||||
public static final String SHOW_SCALE = "show_scale";
|
||||
|
||||
/**
|
||||
* The unit system to be used in the application.
|
||||
*/
|
||||
public static final String UNIT_SYSTEM = "unit_system";
|
||||
|
||||
/**
|
||||
* The temperature unit to be used in the application.
|
||||
*/
|
||||
public static final String TEMPERATURE_UNIT = "temperature_unit";
|
||||
|
||||
/**
|
||||
* Creates the settings with the context.
|
||||
*
|
||||
@@ -166,41 +192,6 @@ public class MowestaSettings extends SdkSettings {
|
||||
e.apply();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether the diagram uses celsius or fahrenheit.
|
||||
*
|
||||
* @return True if the diagram uses celsius, false if fahrenheit
|
||||
*/
|
||||
public boolean isTemperatureCelsius() {
|
||||
boolean defaultValue = getResources().getBoolean(R.bool.temperature_celsius_default);
|
||||
return preferences.getBoolean(TEMPERATURE_CELSIUS, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the boolean to indicate whether the diagram uses fahrenheit
|
||||
* or celsius.
|
||||
*
|
||||
* @param value The value.
|
||||
*/
|
||||
public void setTemperatureCelsius(boolean value) {
|
||||
SharedPreferences.Editor e = preferences.edit();
|
||||
e.putBoolean(TEMPERATURE_CELSIUS, value);
|
||||
e.apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the temperature is in celsisus or fahrenheit without object allocation.
|
||||
*
|
||||
* @param context The context.
|
||||
* @return True if temperature is in celsius.
|
||||
*/
|
||||
public static boolean isTemperatureCelsisus(@NonNull Context context) {
|
||||
boolean defaultValue = context.getResources().getBoolean(R.bool.temperature_celsius_default);
|
||||
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
return preferences.getBoolean(TEMPERATURE_CELSIUS, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the cloud coverage is shown.
|
||||
*
|
||||
@@ -329,6 +320,53 @@ public class MowestaSettings extends SdkSettings {
|
||||
e.apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the temperature unit.
|
||||
*
|
||||
* @return The temperature unit.
|
||||
*/
|
||||
public TemperatureUnit getTemperatureUnit() {
|
||||
int index = preferences.getInt(TEMPERATURE_UNIT, TemperatureUnit.BOTH.ordinal());
|
||||
index = Math.max(0, Math.min(index, TemperatureUnit.values().length - 1));
|
||||
return TemperatureUnit.values()[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the temperature unit.
|
||||
*
|
||||
* @param unit The temperature unit.
|
||||
*/
|
||||
public void setTemperatureUnit(@NonNull TemperatureUnit unit) {
|
||||
SharedPreferences.Editor e = preferences.edit();
|
||||
e.putInt(TEMPERATURE_UNIT, unit.ordinal());
|
||||
e.apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the unit system.
|
||||
*
|
||||
* @return The unit system.
|
||||
*/
|
||||
public UnitSystem getUnitSystem() {
|
||||
int index = preferences.getInt(UNIT_SYSTEM, UnitSystem.BOTH.ordinal());
|
||||
index = Math.max(0, Math.min(index, UnitSystem.values().length - 1));
|
||||
return UnitSystem.values()[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the unit system.
|
||||
*
|
||||
* @param system The unit system.
|
||||
*/
|
||||
public void setUnitSystem(@NonNull UnitSystem system) {
|
||||
SharedPreferences.Editor e = preferences.edit();
|
||||
e.putInt(UNIT_SYSTEM, system.ordinal());
|
||||
e.apply();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.mowesta.android.app.adapter;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.ViewCityEntryBinding;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An adapter for a recycler view.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CityEntryListAdapter extends RecyclerView.Adapter<CityEntryViewHolder> {
|
||||
|
||||
/**
|
||||
* The listener.
|
||||
*/
|
||||
private @NonNull
|
||||
CityEntryViewHolder.OnCitySelectedListener onCitySelectedListener;
|
||||
|
||||
/**
|
||||
* The owner.
|
||||
*/
|
||||
private @NonNull
|
||||
LifecycleOwner lifecycleOwner;
|
||||
|
||||
/**
|
||||
* The cities to observe for updates.
|
||||
*/
|
||||
private @NonNull
|
||||
LiveData<List<City>> cities;
|
||||
|
||||
/**
|
||||
* The current selection.
|
||||
*/
|
||||
private @NonNull
|
||||
LiveData<City> selection;
|
||||
|
||||
/**
|
||||
* Creates a new adapter.
|
||||
*
|
||||
* @param lifecycleOwner The lifecycle owner.
|
||||
* @param onCitySelectedListener The city selection listener.
|
||||
*
|
||||
*/
|
||||
public CityEntryListAdapter(@NonNull LifecycleOwner lifecycleOwner, @NonNull CityEntryViewHolder.OnCitySelectedListener onCitySelectedListener, LiveData<List<City>> cities, LiveData<City> selection) {
|
||||
this.setHasStableIds(true);
|
||||
this.lifecycleOwner = lifecycleOwner;
|
||||
this.onCitySelectedListener = onCitySelectedListener;
|
||||
this.cities = cities;
|
||||
this.selection = selection;
|
||||
cities.observe(lifecycleOwner, (v)-> notifyDataSetChanged());
|
||||
selection.observe(lifecycleOwner, (v)-> notifyDataSetChanged());
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public CityEntryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
ViewCityEntryBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.view_city_entry, parent, false);
|
||||
binding.setLifecycleOwner(lifecycleOwner);
|
||||
binding.setListener(onCitySelectedListener);
|
||||
return new CityEntryViewHolder(binding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull CityEntryViewHolder holder, int position) {
|
||||
City city = getItem(position);
|
||||
holder.setModel(city);
|
||||
holder.setSelected(city != null && selection.getValue() != null && city.getId() != null && city.getId().equals(selection.getValue().getId()));
|
||||
}
|
||||
|
||||
private City getItem(int position) {
|
||||
List<City> c = cities.getValue();
|
||||
return (c == null || position >= c.size()) ? null : c.get(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
List<City> c = cities.getValue();
|
||||
return c == null ? 0: c.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
City c = getItem(position);
|
||||
if (c == null || c.getId() == null)
|
||||
return super.getItemId(position);
|
||||
else return c.getId();
|
||||
}
|
||||
}
|
||||
+5
-16
@@ -22,28 +22,17 @@ import java.util.zip.Inflater;
|
||||
*/
|
||||
public class CityEntryPagedListAdapter extends PagedListAdapter<City, CityEntryViewHolder> {
|
||||
|
||||
/**
|
||||
* A listener that is informed when a city is selected.
|
||||
*/
|
||||
public interface OnCitySelectedListener {
|
||||
|
||||
/**
|
||||
* Called when a city is selected.
|
||||
*
|
||||
* @param city The selected city.
|
||||
*/
|
||||
void onCitySelected(City city);
|
||||
}
|
||||
|
||||
/**
|
||||
* The listener.
|
||||
*/
|
||||
private @NonNull OnCitySelectedListener onCitySelectedListener;
|
||||
private @NonNull
|
||||
CityEntryViewHolder.OnCitySelectedListener onCitySelectedListener;
|
||||
|
||||
/**
|
||||
* The owner.
|
||||
*/
|
||||
private @NonNull LifecycleOwner lifecycleOwner;
|
||||
private @NonNull
|
||||
LifecycleOwner lifecycleOwner;
|
||||
|
||||
/**
|
||||
* Creates a new adapter.
|
||||
@@ -51,7 +40,7 @@ public class CityEntryPagedListAdapter extends PagedListAdapter<City, CityEntryV
|
||||
* @param lifecycleOwner The lifecycle owner.
|
||||
* @param onCitySelectedListener The city selection listener.
|
||||
*/
|
||||
public CityEntryPagedListAdapter(@NonNull LifecycleOwner lifecycleOwner, @NonNull OnCitySelectedListener onCitySelectedListener) {
|
||||
public CityEntryPagedListAdapter(@NonNull LifecycleOwner lifecycleOwner, @NonNull CityEntryViewHolder.OnCitySelectedListener onCitySelectedListener) {
|
||||
super(new Callback());
|
||||
this.lifecycleOwner = lifecycleOwner;
|
||||
this.onCitySelectedListener = onCitySelectedListener;
|
||||
|
||||
@@ -14,6 +14,20 @@ import com.mowesta.android.feign.model.City;
|
||||
*/
|
||||
public class CityEntryViewHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
/**
|
||||
* A listener that is informed when a city is selected.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface OnCitySelectedListener {
|
||||
|
||||
/**
|
||||
* Called when a city is selected.
|
||||
*
|
||||
* @param city The selected city.
|
||||
*/
|
||||
void onCitySelected(City city);
|
||||
}
|
||||
|
||||
/**
|
||||
* The binding to update the contents.
|
||||
@@ -38,4 +52,13 @@ public class CityEntryViewHolder extends RecyclerView.ViewHolder {
|
||||
public void setModel(City city) {
|
||||
this.binding.setModel(city);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the city as selected.
|
||||
*
|
||||
* @param selected True to select.
|
||||
*/
|
||||
public void setSelected(boolean selected) {
|
||||
this.binding.setSelected(selected);
|
||||
}
|
||||
}
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package com.mowesta.android.app.adapter;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.PagedListAdapter;
|
||||
import androidx.recyclerview.widget.DiffUtil;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.ViewDeviceEntryBinding;
|
||||
import com.mowesta.android.app.fragment.DevicesFragment;
|
||||
import com.mowesta.android.app.model.DevicesViewModel;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
|
||||
/**
|
||||
* A list adapter to display the list of devices.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DeviceEntryPagedListAdapter extends PagedListAdapter<Device, DeviceEntryViewHolder> {
|
||||
|
||||
/**
|
||||
* The lifecycle owner.
|
||||
*/
|
||||
private @NonNull
|
||||
LifecycleOwner owner;
|
||||
|
||||
/**
|
||||
* The click listener.
|
||||
*/
|
||||
private @NonNull
|
||||
DeviceEntryViewHolder.OnDeviceSelectedListener listener;
|
||||
|
||||
/**
|
||||
* The selected item.
|
||||
*/
|
||||
private @NonNull
|
||||
LiveData<Device> selection;
|
||||
|
||||
/**
|
||||
* Creates a new paged list adapter that will inform
|
||||
* the listener about click events.
|
||||
*
|
||||
* @param owner The lifecycle owner.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public DeviceEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull DeviceEntryViewHolder.OnDeviceSelectedListener listener) {
|
||||
this(owner, listener, new MutableLiveData<>(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new paged list adapter that will inform
|
||||
* the listener about click events and used the specified
|
||||
* live data to color selections.
|
||||
*
|
||||
* @param owner The lifecycle owner.
|
||||
* @param listener The listener.
|
||||
* @param selection The current selection.
|
||||
*/
|
||||
public DeviceEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull DeviceEntryViewHolder.OnDeviceSelectedListener listener, @NonNull LiveData<Device> selection) {
|
||||
super(new DeviceCallback());
|
||||
this.owner = owner;
|
||||
this.listener = listener;
|
||||
this.selection = selection;
|
||||
selection.observe(owner, (s) -> notifyDataSetChanged());
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public DeviceEntryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
ViewDeviceEntryBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.view_device_entry, parent, false);
|
||||
DeviceEntryViewHolder holder = new DeviceEntryViewHolder(binding);
|
||||
binding.setListener(listener);
|
||||
binding.setLifecycleOwner(owner);
|
||||
return holder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull DeviceEntryViewHolder holder, int position) {
|
||||
Device device = getItem(position);
|
||||
holder.setModel(device);
|
||||
holder.setSelected(device != null && selection.getValue() != null && device.getId() != null && device.getId().equals(selection.getValue().getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A callback to determine whether two devices are the same.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class DeviceCallback extends DiffUtil.ItemCallback<Device> {
|
||||
|
||||
@Override
|
||||
public boolean areItemsTheSame(@NonNull Device oldItem, @NonNull Device newItem) {
|
||||
return oldItem.getId() != null && oldItem.getId().equals(newItem.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean areContentsTheSame(@NonNull Device oldItem, @NonNull Device newItem) {
|
||||
return oldItem.getId() != null && oldItem.getId().equals(newItem.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.mowesta.android.app.adapter;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.databinding.ViewDeviceEntryBinding;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
|
||||
/**
|
||||
* The view holder for the list of devices
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DeviceEntryViewHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
/**
|
||||
* A listener that is informed when a device is selected.
|
||||
*/
|
||||
public interface OnDeviceSelectedListener {
|
||||
|
||||
/**
|
||||
* Called when a device is selected.
|
||||
*
|
||||
* @param device The selected device.
|
||||
*/
|
||||
void onDeviceSelected(Device device);
|
||||
}
|
||||
|
||||
/**
|
||||
* The binding with the device view.
|
||||
*/
|
||||
private ViewDeviceEntryBinding binding;
|
||||
|
||||
/**
|
||||
* Creates a new view holder for the binding.
|
||||
*
|
||||
* @param binding The binding.
|
||||
*/
|
||||
public DeviceEntryViewHolder(@NonNull ViewDeviceEntryBinding binding) {
|
||||
super(binding.getRoot());
|
||||
this.binding = binding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the model.
|
||||
*
|
||||
* @param device The device.
|
||||
*/
|
||||
public void setModel(Device device) {
|
||||
this.binding.setModel(device);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Marks the city as selected.
|
||||
*
|
||||
* @param selected True to select.
|
||||
*/
|
||||
public void setSelected(boolean selected) {
|
||||
this.binding.setSelected(selected);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ import androidx.recyclerview.widget.DiffUtil;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.ViewDiagramEntryBinding;
|
||||
import com.mowesta.android.app.model.DiagramEntry;
|
||||
import com.mowesta.android.app.binding.DiagramEntry;
|
||||
|
||||
/**
|
||||
* A paged list adapter for diagram entries.
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package com.mowesta.android.app.adapter;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.databinding.ViewDiagramEntryBinding;
|
||||
import com.mowesta.android.app.model.DiagramEntry;
|
||||
import com.mowesta.android.app.binding.DiagramEntry;
|
||||
|
||||
/**
|
||||
* A view holder for recycler views that contain diagram entries.
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.mowesta.android.app.adapter;
|
||||
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.LiveData;
|
||||
|
||||
/**
|
||||
* A live data object for preferences that store an enumeration value
|
||||
* as an ordinal int in the preferences.
|
||||
*
|
||||
* @param <T> The type.
|
||||
*/
|
||||
public class EnumPreferenceLiveData<T extends Enum<T>> extends LiveData<T> {
|
||||
|
||||
/**
|
||||
* The key.
|
||||
*/
|
||||
private String key;
|
||||
|
||||
/**
|
||||
* The default value.
|
||||
*/
|
||||
private T defaultValue;
|
||||
|
||||
/**
|
||||
* The enumeration type.
|
||||
*/
|
||||
private Class<T> type;
|
||||
|
||||
/**
|
||||
* The preferences to attach to.
|
||||
*/
|
||||
private SharedPreferences preferences;
|
||||
|
||||
/**
|
||||
* The listener to track changes to the value.
|
||||
*/
|
||||
private SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
|
||||
@Override
|
||||
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String k) {
|
||||
if (key.equals(k)) {
|
||||
T newValue = loadValue();
|
||||
if (newValue != getValue()) {
|
||||
setValue(newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new preference live data object for the shared preferences
|
||||
* using the key assuming that it stores int values that are representing
|
||||
* the ordinal number of the specified enumeration type.
|
||||
*
|
||||
* @param preferences The preferences.
|
||||
* @param type The enumeration type.
|
||||
* @param key The key.
|
||||
* @param defaultValue The default value.
|
||||
*/
|
||||
public EnumPreferenceLiveData(@NonNull SharedPreferences preferences, @NonNull Class<T> type, @NonNull String key, @NonNull T defaultValue) {
|
||||
this.key = key;
|
||||
this.type = type;
|
||||
this.preferences = preferences;
|
||||
this.defaultValue = defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the current value.
|
||||
*
|
||||
* @return The current value.
|
||||
*/
|
||||
private T loadValue() {
|
||||
int index = preferences.getInt(key, defaultValue.ordinal());
|
||||
index = Math.max(0, Math.min(index, type.getEnumConstants().length - 1));
|
||||
return type.getEnumConstants()[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(T value) {
|
||||
super.setValue(value);
|
||||
if (value != loadValue()) {
|
||||
SharedPreferences.Editor e = preferences.edit();
|
||||
e.putInt(key, value.ordinal());
|
||||
e.apply();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActive() {
|
||||
super.onActive();
|
||||
preferences.registerOnSharedPreferenceChangeListener(listener);
|
||||
setValue(loadValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onInactive() {
|
||||
super.onInactive();
|
||||
preferences.unregisterOnSharedPreferenceChangeListener(listener);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.mowesta.android.app.arduino;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* The device configuration of the weather station.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@JsonAutoDetect(creatorVisibility = JsonAutoDetect.Visibility.ANY,
|
||||
fieldVisibility = JsonAutoDetect.Visibility.ANY,
|
||||
getterVisibility = JsonAutoDetect.Visibility.NONE,
|
||||
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
|
||||
setterVisibility = JsonAutoDetect.Visibility.NONE)
|
||||
public class ArduinoConfig {
|
||||
|
||||
/**
|
||||
* The network name of the weather station.
|
||||
*/
|
||||
public static final String ARDUINO_SSID = "MoWeSta - WiFi";
|
||||
/**
|
||||
* The network password of the weather station.
|
||||
*/
|
||||
public static final String ARDUINO_PWD = "mowesta123456wifi";
|
||||
|
||||
/**
|
||||
* The ip address of the weather station.
|
||||
*/
|
||||
public static final String ARDUINO_IP = "192.168.4.1";
|
||||
|
||||
/**
|
||||
* The port of the weather station.
|
||||
*/
|
||||
public static final short ARDUINO_PORT = 8080;
|
||||
|
||||
/** The network ssid field. */
|
||||
@JsonProperty("ssid")
|
||||
private String ssid;
|
||||
/** The network password field. */
|
||||
@JsonProperty("password")
|
||||
private String password;
|
||||
/** The device token field. */
|
||||
@JsonProperty("token")
|
||||
private String token;
|
||||
/** The device id field. */
|
||||
@JsonProperty("id")
|
||||
private String id;
|
||||
/** The ssid field. */
|
||||
@JsonProperty("latitude")
|
||||
private String latitude;
|
||||
/** The ssid field. */
|
||||
@JsonProperty("longitude")
|
||||
private String longitude;
|
||||
|
||||
/**
|
||||
* Creates a new device configuration.
|
||||
*
|
||||
* @param id The device id.
|
||||
* @param token The token.
|
||||
* @param ssid The ssid.
|
||||
* @param password The password.
|
||||
* @param longitude The longitude.
|
||||
* @param latitude The latitude.
|
||||
*/
|
||||
public ArduinoConfig(long id, String token, String ssid, String password, double longitude, double latitude) {
|
||||
this.ssid = ssid;
|
||||
this.token = token;
|
||||
this.password = password;
|
||||
this.id = "" + id;
|
||||
this.latitude = "" + latitude;
|
||||
this.longitude = "" + longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the json representation of the device config.
|
||||
*
|
||||
* @return The json representation.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public String toJson() throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.writeValueAsString(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.mowesta.android.app.arduino;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.Network;
|
||||
import android.net.NetworkCapabilities;
|
||||
import android.net.NetworkRequest;
|
||||
import android.net.wifi.WifiNetworkSpecifier;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
/**
|
||||
* The process to connect to the wifi network for Android Q using
|
||||
* the new api exposed by the connectivity manager. For devices
|
||||
* that are running an Android version lower than Q, use the wifi
|
||||
* variant of the process.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@TargetApi(29)
|
||||
public class ConnectivityTask extends NetworkTask {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "ConnectivityTask";
|
||||
|
||||
/**
|
||||
* The connectivity manager.
|
||||
*/
|
||||
private @NonNull ConnectivityManager manager;
|
||||
|
||||
/**
|
||||
* The callback as long as the request is running.
|
||||
*/
|
||||
private ConnectivityManager.NetworkCallback callback;
|
||||
|
||||
/**
|
||||
* A runnable that will destroy the request.
|
||||
*/
|
||||
private Runnable timeout = () -> {
|
||||
Log.d(TAG, "Wifi connection timeout expired.");
|
||||
abort(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new process.
|
||||
*
|
||||
* @param application The application.
|
||||
* @param listener The listener to keep track of changes.
|
||||
*/
|
||||
public ConnectivityTask(@NonNull Application application, @NonNull OnNetworkChangedListener listener) {
|
||||
super(application, listener);
|
||||
this.manager = (ConnectivityManager)application.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the network.
|
||||
*/
|
||||
private void connect() {
|
||||
WifiNetworkSpecifier.Builder specifier = new WifiNetworkSpecifier.Builder();
|
||||
specifier.setSsid(ArduinoConfig.ARDUINO_SSID);
|
||||
specifier.setWpa2Passphrase(ArduinoConfig.ARDUINO_PWD);
|
||||
NetworkRequest request = new NetworkRequest.Builder()
|
||||
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.setNetworkSpecifier(specifier.build())
|
||||
.build();
|
||||
callback = new ConnectivityManager.NetworkCallback() {
|
||||
@Override
|
||||
public void onAvailable(@NonNull Network network) {
|
||||
super.onAvailable(network);
|
||||
manager.bindProcessToNetwork(network);
|
||||
handler.removeCallbacks(timeout);
|
||||
handler.post(() -> listener.onNetworkChanged(true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLost(@NonNull Network network) {
|
||||
super.onLost(network);
|
||||
handler.postDelayed(timeout, ABORT_TIMEOUT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUnavailable() {
|
||||
super.onUnavailable();
|
||||
handler.postDelayed(timeout, ABORT_TIMEOUT);
|
||||
}
|
||||
};
|
||||
manager.requestNetwork(request, callback);
|
||||
handler.postDelayed(timeout, NETWORK_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the process.
|
||||
*/
|
||||
public void cancel() {
|
||||
abort(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the request and optionally signals the network
|
||||
* as being unavailable.
|
||||
*
|
||||
* @param signal True to signal the failure to the network
|
||||
* listener.
|
||||
*/
|
||||
private void abort(boolean signal) {
|
||||
if (callback != null) {
|
||||
manager.unregisterNetworkCallback(callback);
|
||||
callback = null;
|
||||
}
|
||||
manager.bindProcessToNetwork(null);
|
||||
handler.removeCallbacks(timeout);
|
||||
if (signal) {
|
||||
listener.onNetworkChanged(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.mowesta.android.app.arduino;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
/**
|
||||
* An abstract base class for networking processes that connect to
|
||||
* wifi.
|
||||
*/
|
||||
public abstract class NetworkTask {
|
||||
|
||||
/**
|
||||
* An interface for listeners that need to be informed, if
|
||||
* the network becomes available.
|
||||
*/
|
||||
public interface OnNetworkChangedListener {
|
||||
|
||||
/**
|
||||
* Called when the network becomes available or unavailable.
|
||||
*
|
||||
* @param available True, if available, false otherwise.
|
||||
*/
|
||||
void onNetworkChanged(boolean available);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the process, if we cannot connect after 60 seconds.
|
||||
*/
|
||||
public static final int NETWORK_TIMEOUT = 60000;
|
||||
|
||||
/**
|
||||
* Aborts the process after 10 seconds.
|
||||
*/
|
||||
public static final int ABORT_TIMEOUT = 10000;
|
||||
|
||||
/**
|
||||
* A reference to the application.
|
||||
*/
|
||||
protected @NonNull Application application;
|
||||
|
||||
/**
|
||||
* A reference to the listener.
|
||||
*/
|
||||
protected @NonNull OnNetworkChangedListener listener;
|
||||
|
||||
/**
|
||||
* A handler to register the timeout.
|
||||
*/
|
||||
protected @NonNull Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new networking process.
|
||||
*
|
||||
* @param application The application.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public NetworkTask(@NonNull Application application, @NonNull OnNetworkChangedListener listener) {
|
||||
this.listener = listener;
|
||||
this.application = application;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cancels the process without
|
||||
* signalling it to the listener.
|
||||
*/
|
||||
public abstract void cancel();
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.mowesta.android.app.arduino;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.net.DhcpInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.mowesta.android.sdk.task.AbstractTask;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.Socket;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* A task to transfer the data to the arduino. The task first
|
||||
* waits for a few seconds
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TransferTask {
|
||||
|
||||
/**
|
||||
* A listener to keep track of the completion.
|
||||
*/
|
||||
public interface OnCompletionListener {
|
||||
/**
|
||||
* Called when the process completes.
|
||||
*
|
||||
* @param success True to indicate success, false
|
||||
* to indicate a failure.
|
||||
*/
|
||||
void onCompletion(boolean success);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tag for logging.
|
||||
*/
|
||||
private static final String TAG = "TransferTask";
|
||||
|
||||
/**
|
||||
* The configuration to transfer.
|
||||
*/
|
||||
@NonNull
|
||||
private ArduinoConfig config;
|
||||
|
||||
/**
|
||||
* The listener to call.
|
||||
*/
|
||||
@NonNull
|
||||
private OnCompletionListener listener;
|
||||
|
||||
/**
|
||||
* The canceled flag.
|
||||
*/
|
||||
private boolean canceled;
|
||||
|
||||
/**
|
||||
* The socket, if we are current transmitting.
|
||||
*/
|
||||
private Socket socket;
|
||||
|
||||
/**
|
||||
* The application.
|
||||
*/
|
||||
private Application application;
|
||||
|
||||
/**
|
||||
* The handler to post the result.
|
||||
*/
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates a new task.
|
||||
*
|
||||
* @param application The application.
|
||||
* @param config The config.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public TransferTask(@NonNull Application application, @NonNull ArduinoConfig config, @NonNull OnCompletionListener listener) {
|
||||
this.config = config;
|
||||
this.application = application;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the task.
|
||||
*/
|
||||
public synchronized void cancel() {
|
||||
this.canceled = true;
|
||||
if (socket != null) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the task.
|
||||
*/
|
||||
public void execute() {
|
||||
WifiManager manager = (WifiManager)application.getSystemService(Context.WIFI_SERVICE);
|
||||
AbstractTask.SERIAL_EXECUTOR.execute(() -> {
|
||||
try {
|
||||
// sleep for a couple of seconds, since it
|
||||
// will take some time to get an ip address
|
||||
try {
|
||||
int gateway = (192 & 0xff) << 24 | (168 & 0xff) << 16 | (4 & 0xff) << 8 | (1 & 0xff);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
DhcpInfo info = manager.getDhcpInfo();
|
||||
if (info == null || info.gateway != gateway) {
|
||||
Log.d(TAG, "Waiting for dhcp info.");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.d(TAG, "Failed to wait.");
|
||||
}
|
||||
synchronized (TransferTask.this) {
|
||||
if (canceled) return;
|
||||
Log.d(TAG, "Create socket.");
|
||||
socket = new Socket(ArduinoConfig.ARDUINO_IP, ArduinoConfig.ARDUINO_PORT);
|
||||
}
|
||||
try {
|
||||
Log.d(TAG, "Write data.");
|
||||
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
|
||||
w.write(config.toJson());
|
||||
w.write("\n\n");
|
||||
w.flush();
|
||||
synchronized (TransferTask.this) {
|
||||
if (canceled) return;
|
||||
}
|
||||
Log.d(TAG, "Read data.");
|
||||
BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
||||
boolean success = false;
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
if (line.length() == 0) {
|
||||
break;
|
||||
} else {
|
||||
Log.d(TAG, "Read line: " + line);
|
||||
success = success | line.toLowerCase(Locale.US).contains("success");
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "Post success: " + success);
|
||||
post(success);
|
||||
} finally {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.d(TAG, "Exception while transferring data.", e);
|
||||
post(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts the success value, if not cancelled.
|
||||
*
|
||||
* @param success The success value.
|
||||
*/
|
||||
private void post(boolean success) {
|
||||
handler.post(()-> {
|
||||
if (!canceled) {
|
||||
listener.onCompletion(success);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package com.mowesta.android.app.arduino;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Application;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The network process that connects automatically to the Arduino.
|
||||
* Note that this class is intended for devices that are running
|
||||
* Android versions below Q. For Q, use the connectivity manager
|
||||
* network process.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@SuppressLint("Deprecation")
|
||||
@SuppressWarnings("deprecation")
|
||||
public class WifiTask extends NetworkTask {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "WifiTask";
|
||||
|
||||
/**
|
||||
* The manager.
|
||||
*/
|
||||
private @NonNull WifiManager manager;
|
||||
|
||||
/**
|
||||
* The timeout.
|
||||
*/
|
||||
private @NonNull Runnable timeout = () -> {
|
||||
Log.d(TAG, "Wifi connection timeout expired.");
|
||||
cancel(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* The receiver that is informed when the network state changes.
|
||||
*/
|
||||
private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
|
||||
Log.d(TAG, "Received network state changed.");
|
||||
if (intent.hasExtra(WifiManager.EXTRA_NETWORK_INFO)) {
|
||||
android.net.NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
|
||||
if (info != null) {
|
||||
Log.d(TAG, "Received network info: " + info);
|
||||
if (info.isConnected() && isWifiConnected()) {
|
||||
Log.d(TAG, "Connected to the device network.");
|
||||
if (!didSignalSuccess) {
|
||||
Log.d(TAG, "Signaling success.");
|
||||
didSignalSuccess = true;
|
||||
listener.onNetworkChanged(true);
|
||||
handler.removeCallbacks(timeout);
|
||||
}
|
||||
} else if (didSignalSuccess && (!info.isConnected() || !isWifiConnected())) {
|
||||
Log.d(TAG, "Disconnected after connect, aborting.");
|
||||
handler.postDelayed(timeout, ABORT_TIMEOUT);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Network state changed includes no network info, ignoring.");
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Received unexpected action: " + intent.getAction());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** A flag to memorize whether the stateChangeReceiver is registered. */
|
||||
private boolean stateChangeReceiverRegistered = false;
|
||||
|
||||
/**
|
||||
* The wifi configuration that we might have added, if any.
|
||||
*/
|
||||
private int networkId = -1;
|
||||
|
||||
/**
|
||||
* A flag to memorize whether we enabled wifi.
|
||||
*/
|
||||
private boolean didEnableWifi = false;
|
||||
|
||||
/**
|
||||
* A flag to memorize whether we already signaled success.
|
||||
*/
|
||||
private boolean didSignalSuccess = false;
|
||||
|
||||
/**
|
||||
* Creates a new task.
|
||||
*
|
||||
* @param application The application.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public WifiTask(@NonNull Application application, @NonNull OnNetworkChangedListener listener) {
|
||||
super(application, listener);
|
||||
manager = (WifiManager)application.getSystemService(Context.WIFI_SERVICE);
|
||||
connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the task starts to configure the wifi networks.
|
||||
*/
|
||||
private void connect() {
|
||||
try {
|
||||
if (! manager.isWifiEnabled()) {
|
||||
Log.d(TAG, "Wifi was disabled, turning it on.");
|
||||
didEnableWifi = manager.setWifiEnabled(true);
|
||||
}
|
||||
android.net.wifi.WifiConfiguration existing = findConfiguration();
|
||||
if (existing == null) {
|
||||
networkId = manager.addNetwork(createConfiguration());
|
||||
manager.saveConfiguration();
|
||||
}
|
||||
stateChangeReceiverRegistered = true;
|
||||
application.registerReceiver(stateChangeReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
|
||||
if (isWifiConnected()) {
|
||||
Log.d(TAG, "Wifi was connected already.");
|
||||
didSignalSuccess = true;
|
||||
listener.onNetworkChanged(true);
|
||||
} else {
|
||||
Log.d(TAG, "Wifi network is wrong, trigger detection.");
|
||||
manager.disconnect();
|
||||
if (existing != null) {
|
||||
manager.enableNetwork(existing.networkId, true);
|
||||
} else {
|
||||
manager.enableNetwork(networkId, true);
|
||||
}
|
||||
manager.reconnect();
|
||||
}
|
||||
handler.postDelayed(timeout, NETWORK_TIMEOUT);
|
||||
} catch (SecurityException e) {
|
||||
Log.d(TAG, "Failed to connect due to security exception.", e);
|
||||
cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the network is connected to a mowesta device.
|
||||
*
|
||||
* @return True if connected, false otherwise.
|
||||
*/
|
||||
private boolean isWifiConnected() {
|
||||
WifiInfo info = manager.getConnectionInfo();
|
||||
if (info != null) {
|
||||
Log.d(TAG, "Connected to network: " + info.getSSID());
|
||||
return getSsid().equals(info.getSSID());
|
||||
} else {
|
||||
Log.d(TAG, "Not connected to network.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the maximum network priority.
|
||||
*
|
||||
* @return The maximum network priority.
|
||||
* @throws SecurityException Thrown if we are missing a permission.
|
||||
*/
|
||||
private int getMaximumPriority() throws SecurityException {
|
||||
int result = 1;
|
||||
List<android.net.wifi.WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (android.net.wifi.WifiConfiguration configuration: configurations) {
|
||||
result = Math.max(result, configuration.priority);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the mowesta network configuration, if present.
|
||||
*
|
||||
* @return The network configuration, if present already.
|
||||
* @throws SecurityException Thrown if we are missing a permission.
|
||||
*/
|
||||
private android.net.wifi.WifiConfiguration findConfiguration() throws SecurityException {
|
||||
String ssid = getSsid();
|
||||
List<android.net.wifi.WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (android.net.wifi.WifiConfiguration configuration: configurations) {
|
||||
if (ssid.equals(configuration.SSID)) {
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the network configuration for a wpa2 wifi network.
|
||||
*
|
||||
* @return The network configuration.
|
||||
*/
|
||||
private android.net.wifi.WifiConfiguration createConfiguration() {
|
||||
android.net.wifi.WifiConfiguration result = new android.net.wifi.WifiConfiguration();
|
||||
result.SSID = getSsid();
|
||||
result.allowedAuthAlgorithms.set(android.net.wifi.WifiConfiguration.AuthAlgorithm.OPEN);
|
||||
result.allowedProtocols.set(android.net.wifi.WifiConfiguration.Protocol.RSN); // For WPA2
|
||||
result.allowedKeyManagement.set(android.net.wifi.WifiConfiguration.KeyMgmt.WPA_PSK);
|
||||
result.allowedKeyManagement.set(android.net.wifi.WifiConfiguration.KeyMgmt.WPA_EAP);
|
||||
result.allowedPairwiseCiphers.set(android.net.wifi.WifiConfiguration.PairwiseCipher.TKIP);
|
||||
result.allowedPairwiseCiphers.set(android.net.wifi.WifiConfiguration.PairwiseCipher.CCMP);
|
||||
result.allowedGroupCiphers.set(android.net.wifi.WifiConfiguration.GroupCipher.TKIP);
|
||||
result.allowedGroupCiphers.set(android.net.wifi.WifiConfiguration.GroupCipher.CCMP);
|
||||
result.preSharedKey = String.format("\"%s\"", ArduinoConfig.ARDUINO_PWD);
|
||||
result.status = android.net.wifi.WifiConfiguration.Status.ENABLED;
|
||||
try {
|
||||
int priority = getMaximumPriority() + 400;
|
||||
Log.d(TAG, "Setting maximum priority to " + priority + ".");
|
||||
result.priority = priority;
|
||||
} catch (SecurityException e) {
|
||||
Log.d(TAG, "Failed to get priority, using default value.", e);
|
||||
result.priority = 500;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the mowesta wifi configuration, if we have added it.
|
||||
*/
|
||||
private void removeConfiguration() {
|
||||
if (networkId != -1) {
|
||||
manager.removeNetwork(networkId);
|
||||
manager.saveConfiguration();
|
||||
networkId = -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters the network listener.
|
||||
*/
|
||||
private void removeStateChangeReceiver() {
|
||||
if (stateChangeReceiverRegistered) {
|
||||
application.unregisterReceiver(stateChangeReceiver);
|
||||
stateChangeReceiverRegistered = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables wifi, if we enabled it.
|
||||
*/
|
||||
private void disableWifi() {
|
||||
if (didEnableWifi) {
|
||||
manager.setWifiEnabled(false);
|
||||
didEnableWifi = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ssid of the mowesta device.
|
||||
*
|
||||
* @return The ssid.
|
||||
*/
|
||||
private String getSsid() {
|
||||
return String.format("\"%s\"", ArduinoConfig.ARDUINO_SSID);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
cancel(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the process and optionally signals it.
|
||||
*
|
||||
* @param signal True to signal the event.
|
||||
*/
|
||||
private void cancel(boolean signal) {
|
||||
removeConfiguration();
|
||||
removeStateChangeReceiver();
|
||||
disableWifi();
|
||||
handler.removeCallbacks(timeout);
|
||||
if (signal) {
|
||||
listener.onNetworkChanged(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-44
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.android.app.model;
|
||||
package com.mowesta.android.app.binding;
|
||||
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
@@ -14,9 +15,9 @@ import androidx.databinding.BindingAdapter;
|
||||
import com.google.android.material.textfield.TextInputLayout;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.model.FormStatus;
|
||||
import com.mowesta.android.app.util.DateFormatter;
|
||||
import com.mowesta.android.app.view.WeatherIcon;
|
||||
import com.mowesta.android.app.view.WeatherView;
|
||||
import com.mowesta.android.app.util.UnitUtils;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.Country;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
@@ -57,7 +58,7 @@ public class BindingAdapters {
|
||||
*/
|
||||
@BindingAdapter("err")
|
||||
public static void setFormStatus(TextInputLayout input, FormStatus status) {
|
||||
if (status.isValid()) {
|
||||
if (status == null || status.isValid()) {
|
||||
input.setError(null);
|
||||
} else {
|
||||
if (status.getMessage() == 0) {
|
||||
@@ -227,6 +228,12 @@ public class BindingAdapters {
|
||||
case TOWN:
|
||||
res = R.string.city_type_town;
|
||||
break;
|
||||
case SUBURB:
|
||||
res = R.string.city_type_suburb;
|
||||
break;
|
||||
case VILLAGE:
|
||||
res = R.string.city_type_village;
|
||||
break;
|
||||
}
|
||||
if (city.isCapital()) {
|
||||
res = R.string.city_type_capital;
|
||||
@@ -330,7 +337,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("stationAltitude")
|
||||
public static void setStationAltitude(@NonNull TextView view, @Nullable WeatherStation station) {
|
||||
if (station == null || station.getAltitude() == null) view.setText("");
|
||||
else view.setText(view.getResources().getString(R.string.format_altitude, station.getAltitude()));
|
||||
else view.setText(UnitUtils.toSpanned(UnitUtils.getAltitude(view.getContext(), station.getAltitude())));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -368,9 +375,7 @@ public class BindingAdapters {
|
||||
public static void setTemperature(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getTemperature() == null) view.setText("");
|
||||
else {
|
||||
int centigrade = (int) Math.round(condition.getTemperature());
|
||||
int fahrenheit = (int) Math.round((condition.getTemperature() * 9 / 5) + 32);
|
||||
view.setText(view.getContext().getResources().getString(R.string.format_temperature, centigrade, fahrenheit));
|
||||
view.setText(UnitUtils.toSpanned(UnitUtils.getTemperature(view.getContext(), condition.getTemperature())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,7 +388,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("humidity")
|
||||
public static void setHumidity(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getHumidity() == null) view.setText("");
|
||||
else view.setText(view.getContext().getResources().getString(R.string.format_humidity, condition.getHumidity()));
|
||||
else view.setText(UnitUtils.toSpanned(view.getContext().getResources().getString(R.string.format_humidity, condition.getHumidity())));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -395,7 +400,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("cloudCoverage")
|
||||
public static void setCloudCoverage(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getCloudCoverage() == null) view.setText("");
|
||||
else view.setText(view.getContext().getResources().getString(R.string.format_cloud_coverage, condition.getCloudCoverage() * 100));
|
||||
else view.setText(UnitUtils.toSpanned(view.getContext().getResources().getString(R.string.format_cloud_coverage, condition.getCloudCoverage() * 100)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -407,7 +412,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("pressure")
|
||||
public static void setPressure(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getPressure() == null) view.setText("");
|
||||
else view.setText(view.getContext().getResources().getString(R.string.format_pressure, condition.getPressure()));
|
||||
else view.setText(UnitUtils.toSpanned(UnitUtils.getPressure(view.getContext(), condition.getPressure())));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -420,9 +425,7 @@ public class BindingAdapters {
|
||||
public static void setWindSpeed(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getWindSpeed() == null) view.setText("");
|
||||
else {
|
||||
int kmph = (int) Math.round(condition.getWindSpeed() * 3.6);
|
||||
int mph = (int) Math.round(condition.getWindSpeed() * 3.6 * 0.6213711922373339136);
|
||||
view.setText(view.getContext().getResources().getString(R.string.format_wind_speed, kmph, mph));
|
||||
view.setText(UnitUtils.toSpanned(UnitUtils.getWindSpeed(view.getContext(), condition.getWindSpeed())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +438,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("precipitation")
|
||||
public static void setPrecipitation(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getPrecipitation() == null) view.setText("");
|
||||
else view.setText(view.getContext().getResources().getString(R.string.format_precipitation, condition.getPrecipitation()));
|
||||
else view.setText(UnitUtils.toSpanned(UnitUtils.getPrecipitation(view.getContext(), condition.getPrecipitation())));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,7 +450,7 @@ public class BindingAdapters {
|
||||
@BindingAdapter("snow")
|
||||
public static void setSnow(TextView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getSnowDepth() == null) view.setText("");
|
||||
else view.setText(view.getContext().getResources().getString(R.string.format_snow, condition.getSnowDepth()));
|
||||
else view.setText(UnitUtils.toSpanned(UnitUtils.getSnowDepth(view.getContext(), condition.getSnowDepth())));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -471,15 +474,19 @@ public class BindingAdapters {
|
||||
* @param condition The weather condition.
|
||||
*/
|
||||
@BindingAdapter("weatherIcon")
|
||||
public static void setWeatherIcon(WeatherView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getType() == null) {
|
||||
view.setText("");
|
||||
public static void setWeatherIcon(ImageView view, @Nullable WeatherCondition condition) {
|
||||
Integer resource = null;
|
||||
if (condition != null && condition.getType() != null) {
|
||||
resource = BindingTransforms.getIcon(condition.getType(), false);
|
||||
}
|
||||
if (resource == null) {
|
||||
view.setImageResource(android.R.color.transparent);
|
||||
view.setContentDescription(null);
|
||||
TooltipCompat.setTooltipText(view, null);
|
||||
} else {
|
||||
int res = BindingTransforms.getText(condition.getType());
|
||||
String str = view.getContext().getString(res);
|
||||
view.setType(BindingTransforms.getIcon(condition.getType(), false));
|
||||
view.setImageResource(resource);
|
||||
view.setContentDescription(str);
|
||||
TooltipCompat.setTooltipText(view, str);
|
||||
}
|
||||
@@ -492,16 +499,16 @@ public class BindingAdapters {
|
||||
* @param condition The weather condition.
|
||||
*/
|
||||
@BindingAdapter("directionIcon")
|
||||
public static void setDirectionIcon(WeatherView view, @Nullable WeatherCondition condition) {
|
||||
public static void setDirectionIcon(ImageView view, @Nullable WeatherCondition condition) {
|
||||
if (condition == null || condition.getWindDirection() == null) {
|
||||
view.setType(null);
|
||||
view.setImageResource(android.R.color.transparent);
|
||||
view.setRotation(0);
|
||||
view.setContentDescription(null);
|
||||
TooltipCompat.setTooltipText(view, null);
|
||||
} else {
|
||||
int res = BindingTransforms.getText(condition.getWindDirection());
|
||||
String str = view.getContext().getString(res);
|
||||
view.setType(WeatherIcon.WIND_DIRECTION);
|
||||
view.setImageResource(R.drawable.ic_wind_deg_normal_24);
|
||||
view.setRotation(BindingTransforms.getRotation(condition.getWindDirection()));
|
||||
view.setContentDescription(str);
|
||||
TooltipCompat.setTooltipText(view, str);
|
||||
@@ -590,8 +597,7 @@ public class BindingAdapters {
|
||||
view.setVisibility(View.GONE);
|
||||
} else {
|
||||
view.setVisibility(View.VISIBLE);
|
||||
float temp = BindingTransforms.getTemperature(view.getContext(), entry.getTemperature().getAbsoluteValue());
|
||||
view.setText(view.getResources().getString(R.string.format_compact, temp));
|
||||
view.setText(UnitUtils.getDiagramTemperature(view.getContext(), entry.getTemperature().getAbsoluteValue()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,7 +607,7 @@ public class BindingAdapters {
|
||||
view.setVisibility(View.GONE);
|
||||
} else {
|
||||
view.setVisibility(View.VISIBLE);
|
||||
view.setText(view.getResources().getString(R.string.format_compact, (float)entry.getPressure().getAbsoluteValue()));
|
||||
view.setText(UnitUtils.getDiagramPressure(view.getContext(), entry.getPressure().getAbsoluteValue()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -621,9 +627,7 @@ public class BindingAdapters {
|
||||
if (data == null) {
|
||||
view.setText(R.string.label_not_available);
|
||||
} else {
|
||||
int centigrade = (int) Math.round(data);
|
||||
int fahrenheit = (int) Math.round((data * 9 / 5) + 32);
|
||||
view.setText(view.getContext().getResources().getString(R.string.format_temperature, centigrade, fahrenheit));
|
||||
view.setText(UnitUtils.toSpanned(UnitUtils.getTemperature(view.getContext(), data)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,7 +636,7 @@ public class BindingAdapters {
|
||||
if (data == null) {
|
||||
view.setText(R.string.label_not_available);
|
||||
} else {
|
||||
view.setText(view.getResources().getString(R.string.format_pressure, data.floatValue()));
|
||||
view.setText(UnitUtils.toSpanned(UnitUtils.getPressure(view.getContext(), data)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,7 +645,7 @@ public class BindingAdapters {
|
||||
if (data == null) {
|
||||
view.setText(R.string.label_not_available);
|
||||
} else {
|
||||
view.setText(view.getResources().getString(R.string.format_humidity, data.floatValue()));
|
||||
view.setText(UnitUtils.toSpanned(view.getResources().getString(R.string.format_humidity, data.floatValue())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,7 +817,8 @@ public class BindingAdapters {
|
||||
|
||||
|
||||
@BindingAdapter("measurementValue")
|
||||
public static void setMeasurementValue(TextView view, @Nullable MeasurementViewModel.MeasurementValue value) {
|
||||
public static void setMeasurementValue(TextView view, @Nullable MeasurementValue value) {
|
||||
Resources r = view.getContext().getResources();
|
||||
if (value == null || !value.hasValue()) {
|
||||
view.setText(null);
|
||||
} else {
|
||||
@@ -823,17 +828,30 @@ public class BindingAdapters {
|
||||
String valueText = null;
|
||||
if (o != null) {
|
||||
if (o instanceof Boolean) {
|
||||
valueText = view.getResources().getString(((Boolean)o) ? R.string.measurement_data_true : R.string.measurement_data_false);
|
||||
valueText = r.getString(((Boolean)o) ? R.string.measurement_data_true : R.string.measurement_data_false);
|
||||
} else if (o instanceof Double) {
|
||||
int format = BindingTransforms.getMeasurementTypeFormat(value.getType());
|
||||
if (format == 0) {
|
||||
valueText = o.toString();
|
||||
} else if (format == R.string.format_temperature) {
|
||||
int centigrade = (int) Math.round((Double)o);
|
||||
int fahrenheit = (int) Math.round((((Double)o) * 9 / 5) + 32);
|
||||
valueText = view.getResources().getString(R.string.format_temperature, centigrade, fahrenheit);
|
||||
} else {
|
||||
valueText = view.getResources().getString(format, ((Double)o).floatValue());
|
||||
switch (value.getType()) {
|
||||
case CPU_FREQUENCY:
|
||||
valueText = r.getString(R.string.format_frequency, ((Double)o).floatValue() / 1000000);
|
||||
break;
|
||||
case SOLAR_VOLTAGE:
|
||||
case BATTERY_VOLTAGE:
|
||||
valueText = r.getString(R.string.format_voltage, ((Double)o).floatValue());
|
||||
break;
|
||||
case SENSOR_HUMIDITY:
|
||||
valueText = r.getString(R.string.format_humidity, ((Double)o).floatValue());
|
||||
break;
|
||||
case SENSOR_PRESSURE:
|
||||
valueText = UnitUtils.getPressure(view.getContext(), (Double)o).toString();
|
||||
break;
|
||||
case CPU_TEMPERATURE:
|
||||
case BATTERY_TEMPERATURE:
|
||||
case SENSOR_TEMPERATURE:
|
||||
valueText = UnitUtils.getTemperature(view.getContext(), (Double)o).toString();
|
||||
break;
|
||||
default:
|
||||
valueText = o.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -845,12 +863,12 @@ public class BindingAdapters {
|
||||
}
|
||||
}
|
||||
}
|
||||
view.setText(text);
|
||||
view.setText(UnitUtils.toSpanned(text));
|
||||
}
|
||||
}
|
||||
|
||||
@BindingAdapter("measurementVisibility")
|
||||
public static void setMeasurementVisibility(View view, @Nullable MeasurementViewModel.MeasurementValue value) {
|
||||
public static void setMeasurementVisibility(View view, @Nullable MeasurementValue value) {
|
||||
if (value == null || !value.hasValue()) {
|
||||
view.setVisibility(View.GONE);
|
||||
} else {
|
||||
+26
-100
@@ -1,14 +1,11 @@
|
||||
package com.mowesta.android.app.model;
|
||||
package com.mowesta.android.app.binding;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.view.JamIcon;
|
||||
import com.mowesta.android.app.view.WeatherIcon;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
import com.mowesta.android.feign.model.WeatherCondition;
|
||||
import com.mowesta.android.feign.model.WeatherVideo;
|
||||
@@ -23,23 +20,6 @@ import java.util.Map;
|
||||
public class BindingTransforms {
|
||||
|
||||
|
||||
/**
|
||||
* Returns the temperature as float in celsius or fahrenheit based on
|
||||
* the user's current settings.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param celsius The temperature in celsius.
|
||||
* @return The temperature in celsisus or fahrenheit.
|
||||
*/
|
||||
public static float getTemperature(@NonNull Context context, double celsius) {
|
||||
if (MowestaSettings.isTemperatureCelsisus(context)) {
|
||||
return (float)celsius;
|
||||
} else {
|
||||
return (float) Math.round((celsius * 9 / 5) + 32);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the best (non-null) name from a map of names given the current
|
||||
* language settings and the preference for short values.
|
||||
@@ -236,6 +216,8 @@ public class BindingTransforms {
|
||||
return R.string.video_type_pressure;
|
||||
case PRECIPITATION:
|
||||
return R.string.video_type_precipitation;
|
||||
case WIND:
|
||||
return R.string.video_type_wind;
|
||||
default:
|
||||
return R.string.video_type_temperature;
|
||||
}
|
||||
@@ -251,56 +233,56 @@ public class BindingTransforms {
|
||||
* to return the regular (day) representation.
|
||||
* @return The weather icon, which may be null.
|
||||
*/
|
||||
public static @Nullable WeatherIcon getIcon(@Nullable WeatherCondition.TypeEnum value, boolean alternate) {
|
||||
public static @Nullable Integer getIcon(@Nullable WeatherCondition.TypeEnum value, boolean alternate) {
|
||||
if (value == null) return null;
|
||||
switch (value) {
|
||||
case UNKNOWN:
|
||||
break;
|
||||
case CLEAR_SKY:
|
||||
case MAINLY_CLEAR:
|
||||
return alternate ? WeatherIcon.NIGHT_CLEAR : WeatherIcon.DAY_SUNNY;
|
||||
return alternate ? R.drawable.ic_night_clear_normal_24 : R.drawable.ic_day_sunny_normal_24;
|
||||
case PARTLY_CLOUDY:
|
||||
return alternate ? WeatherIcon.NIGHT_CLOUDY : WeatherIcon.DAY_CLOUDY;
|
||||
return alternate ? R.drawable.ic_night_cloudy_normal_24 : R.drawable.ic_day_cloudy_normal_24;
|
||||
case CLOUDY:
|
||||
return WeatherIcon.CLOUDY;
|
||||
return R.drawable.ic_cloudy_normal_24;
|
||||
case FOG:
|
||||
case FOG_DEPOSITING_RIME:
|
||||
return alternate ? WeatherIcon.NIGHT_FOG : WeatherIcon.DAY_FOG;
|
||||
return alternate ? R.drawable.ic_night_fog_normal_24 : R.drawable.ic_day_fog_normal_24;
|
||||
case SLIGHT_DRIZZLE:
|
||||
case MODERATE_DRIZZLE:
|
||||
return alternate ? WeatherIcon.NIGHT_SPRINKLE : WeatherIcon.DAY_SPRINKLE;
|
||||
return alternate ? R.drawable.ic_night_sprinkle_normal_24 : R.drawable.ic_day_sprinkle_normal_24;
|
||||
case HEAVY_DRIZZLE:
|
||||
return WeatherIcon.SPRINKLE;
|
||||
return R.drawable.ic_sprinkle_normal_24;
|
||||
case DRIZZLE_FREEZING_SLIGHT:
|
||||
case RAIN_FREEZING_SLIGHT:
|
||||
case DRIZZLE_FREEZING_MODERATE_HEAVY:
|
||||
case RAIN_FREEZING_MODERATE_HEAVY:
|
||||
return WeatherIcon.SNOWFLAKE_COLD;
|
||||
return R.drawable.ic_snowflake_cold_normal_24;
|
||||
case SLIGHT_RAIN_NOT_FREEZING:
|
||||
case MODERATE_RAIN_NOT_FREEZING:
|
||||
return alternate ? WeatherIcon.NIGHT_RAIN : WeatherIcon.DAY_RAIN;
|
||||
return alternate ? R.drawable.ic_night_rain_normal_24 : R.drawable.ic_day_rain_normal_24;
|
||||
case HEAVY_RAIN_NOT_FREEZING:
|
||||
return WeatherIcon.RAIN;
|
||||
return R.drawable.ic_rain_normal_24;
|
||||
case SLIGHT_FALL_OF_SNOWFLAKES:
|
||||
case MODERATE_FALL_OF_SNOWFLAKES:
|
||||
return alternate ? WeatherIcon.NIGHT_SNOW : WeatherIcon.DAY_SNOW;
|
||||
return alternate ? R.drawable.ic_night_snow_normal_24 : R.drawable.ic_day_snow_normal_24;
|
||||
case HEAVY_FALL_OF_SNOWFLAKES:
|
||||
case SNOW_GRAINS:
|
||||
return WeatherIcon.SNOW;
|
||||
return R.drawable.ic_snow_normal_24;
|
||||
case RAIN_SHOWER_SLIGHT:
|
||||
return alternate ? WeatherIcon.NIGHT_SHOWERS : WeatherIcon.DAY_SHOWERS;
|
||||
return alternate ? R.drawable.ic_night_showers_normal_24 : R.drawable.ic_day_showers_normal_24;
|
||||
case RAIN_SHOWER_MODERATE_HEAVY:
|
||||
return WeatherIcon.SHOWERS;
|
||||
return R.drawable.ic_showers_normal_24;
|
||||
case RAIN_SHOWER_VIOLENT:
|
||||
return WeatherIcon.STORM_SHOWERS;
|
||||
return R.drawable.ic_storm_showers_normal_24;
|
||||
case SNOW_SHOWER_SLIGHT:
|
||||
return alternate ? WeatherIcon.NIGHT_RAIN_MIX : WeatherIcon.DAY_RAIN_MIX;
|
||||
return alternate ? R.drawable.ic_night_rain_mix_normal_24 : R.drawable.ic_day_rain_mix_normal_24;
|
||||
case SNOW_SHOWER_MODERATE_HEAVY:
|
||||
return WeatherIcon.RAIN_MIX;
|
||||
return R.drawable.ic_rain_mix_normal_24;
|
||||
case THUNDERSTORM_SLIGHT_MODERATE:
|
||||
return alternate ? WeatherIcon.NIGHT_THUNDERSTORM : WeatherIcon.DAY_THUNDERSTORM;
|
||||
return alternate ? R.drawable.ic_night_thunderstorm_normal_24 : R.drawable.ic_day_thunderstorm_normal_24;
|
||||
case THUNDERSTORM_HAIL_HEAVY:
|
||||
return WeatherIcon.THUNDERSTORM;
|
||||
return R.drawable.ic_thunderstorm_normal_24;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -312,6 +294,7 @@ public class BindingTransforms {
|
||||
* @return The label.
|
||||
*/
|
||||
public static int getOsLabel(Device.OsEnum os) {
|
||||
if (os == null) return 0;
|
||||
switch (os) {
|
||||
case IOS:
|
||||
return R.string.label_device_type_ios;
|
||||
@@ -330,13 +313,14 @@ public class BindingTransforms {
|
||||
* @return The icon.
|
||||
*/
|
||||
public static int getOsIcon(Device.OsEnum os) {
|
||||
if (os == null) return 0;
|
||||
switch (os) {
|
||||
case IOS:
|
||||
return R.drawable.ic_phone_iphone_normal_24;
|
||||
case ANDROID:
|
||||
return R.drawable.ic_android_normal_24;
|
||||
case ARDUINO:
|
||||
return R.drawable.ic_memory_black_24dp;
|
||||
return R.drawable.ic_memory_normal_24dp;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -347,7 +331,7 @@ public class BindingTransforms {
|
||||
* @param type the type.
|
||||
* @return The label or 0 if the type is null.
|
||||
*/
|
||||
public static int getMeasurementTypeLabel(MeasurementViewModel.MeasurementType type) {
|
||||
public static int getMeasurementTypeLabel(MeasurementType type) {
|
||||
switch (type) {
|
||||
case CPU_FREQUENCY:
|
||||
return R.string.measurement_type_cpu_frequency;
|
||||
@@ -373,64 +357,6 @@ public class BindingTransforms {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the format to be used for the measurement type, if the type's data is double.
|
||||
*
|
||||
* @param type The type.
|
||||
* @return The format or 0.
|
||||
*/
|
||||
public static int getMeasurementTypeFormat(MeasurementViewModel.MeasurementType type) {
|
||||
switch (type) {
|
||||
case CPU_FREQUENCY:
|
||||
return R.string.format_frequency;
|
||||
case SOLAR_VOLTAGE:
|
||||
case BATTERY_VOLTAGE:
|
||||
return R.string.format_voltage;
|
||||
case SENSOR_HUMIDITY:
|
||||
return R.string.format_humidity;
|
||||
case SENSOR_PRESSURE:
|
||||
return R.string.format_pressure;
|
||||
case CPU_TEMPERATURE:
|
||||
case BATTERY_TEMPERATURE:
|
||||
case SENSOR_TEMPERATURE:
|
||||
return R.string.format_temperature;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the jam icon for the measurement type.
|
||||
*
|
||||
* @param type The measurement type.
|
||||
* @return The jam icon.
|
||||
*/
|
||||
public static JamIcon getMeasurementTypeIcon(MeasurementViewModel.MeasurementType type) {
|
||||
switch (type) {
|
||||
case CPU_FREQUENCY:
|
||||
return JamIcon.JAM_ACTIVITY;
|
||||
case SOLAR_VOLTAGE:
|
||||
return JamIcon.JAM_SUN;
|
||||
case SCREEN_ENABLED:
|
||||
return JamIcon.JAM_SCREEN;
|
||||
case BATTERY_VOLTAGE:
|
||||
return JamIcon.JAM_BATTERY_HALF_F;
|
||||
case CPU_TEMPERATURE:
|
||||
return JamIcon.JAM_PHONE;
|
||||
case SENSOR_HUMIDITY:
|
||||
return JamIcon.JAM_WATER_DROP;
|
||||
case SENSOR_PRESSURE:
|
||||
return JamIcon.JAM_DASHBOARD;
|
||||
case BATTERY_CHARGING:
|
||||
return JamIcon.JAM_BATTERY_CHARGING;
|
||||
case BATTERY_TEMPERATURE:
|
||||
return JamIcon.JAM_BATTERY;
|
||||
case SENSOR_TEMPERATURE:
|
||||
return JamIcon.JAM_TEMPERATURE;
|
||||
}
|
||||
return JamIcon.JAM_INFO;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package com.mowesta.android.app.model;
|
||||
package com.mowesta.android.app.binding;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -195,7 +195,7 @@ public class DiagramEntry<T> {
|
||||
*/
|
||||
public static DiagramEntry<Measurement> from(Measurement measurement) {
|
||||
DiagramValue temperature = createValue(measurement.getTemperature(), -40, 40);
|
||||
DiagramValue humidity = createValue(measurement.getHumidity(), 0, 1);
|
||||
DiagramValue humidity = createValue(measurement.getHumidity(), 0, 100);
|
||||
DiagramValue pressure = createValue(measurement.getPressure(), 700, 1200);
|
||||
return new DiagramEntry<>(measurement.getId(), measurement.getTime(), measurement, temperature, humidity, pressure);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.mowesta.android.app.binding;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The types of measurement context.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
public enum MeasurementType {
|
||||
|
||||
/**
|
||||
* A boolean to identify whether the battery is charging.
|
||||
* e.g. true false
|
||||
*/
|
||||
BATTERY_CHARGING(Boolean.class),
|
||||
|
||||
/**
|
||||
* The temperature reading of the battery (double value in centigrade, can be read through ACTION_BATTERY_CHANGED).
|
||||
* e.g. 37.1, -1.3
|
||||
*/
|
||||
BATTERY_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* A temperature reading of a temperature sensor (double value in centigrade, TYPE_TEMERATURE on Android).
|
||||
* e.g. 37.1, -1.3
|
||||
*/
|
||||
SENSOR_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* A pressure reading of a barometer sensor (double value in hPa, TYPE_BAROMETER on Android).
|
||||
* e.g. 1000.0, 998.26127
|
||||
*/
|
||||
SENSOR_PRESSURE(Double.class),
|
||||
|
||||
/**
|
||||
* A humidity reading of a humidity sensor (double value as relative humidity in %, TYPE_RELATIVE_HUMIDITY on Android).
|
||||
* range: 0-1 (0->0%, 1->100%, 0.5->50%)
|
||||
*/
|
||||
SENSOR_HUMIDITY(Double.class),
|
||||
|
||||
/**
|
||||
* The temperature of the cpu (double value in centigrade, can be read by analyzing the proc file system).
|
||||
* e.g. 37.1 -1.3
|
||||
*/
|
||||
CPU_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* The current frequency of the cpu (double value in mhz, can be read by analyzing the proc file system).
|
||||
*/
|
||||
CPU_FREQUENCY(Double.class),
|
||||
|
||||
/**
|
||||
* A boolean to determine whether the screen is on (true) or off (false).
|
||||
*/
|
||||
SCREEN_ENABLED(Boolean.class),
|
||||
|
||||
/**
|
||||
* The voltage of the battery (used to monitor the battery of the weather station).
|
||||
* e.g. 3.77 -> 3.77 Volt
|
||||
*/
|
||||
BATTERY_VOLTAGE(Double.class),
|
||||
|
||||
/**
|
||||
* The voltage of the solar panel (used to estimate whether the weather station is located in the sun).
|
||||
* e.g. 3.77 -> 3.77 Volt
|
||||
*/
|
||||
SOLAR_VOLTAGE(Double.class);
|
||||
|
||||
/**
|
||||
* The data type.
|
||||
*/
|
||||
private Class<?> type;
|
||||
|
||||
/**
|
||||
* Creates a measurement type with the specified data type.
|
||||
*
|
||||
* @param type The data type expected for the measurement.
|
||||
*/
|
||||
private MeasurementType(Class<?> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data type.
|
||||
*
|
||||
* @return The data type.
|
||||
*/
|
||||
public Class<?> getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the data and returns a java array with the type
|
||||
* represented by this constant or an empty array, if the
|
||||
* data cannot be parsed.
|
||||
*
|
||||
* @param value The value to parse.
|
||||
* @return The java object.
|
||||
*/
|
||||
public Object[] getValues(String value) {
|
||||
List<Object> result = new ArrayList<>();
|
||||
if (value != null) {
|
||||
String[] substrings = value.split(",");
|
||||
if (type == Boolean.class) {
|
||||
for (String s : substrings) {
|
||||
Boolean b = (Boolean) parseValue(s);
|
||||
if (b != null) result.add(b);
|
||||
}
|
||||
} else if (type == Double.class) {
|
||||
for (String s : substrings) {
|
||||
Double d = (Double) parseValue(s);
|
||||
if (d != null) result.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.toArray(new Object[result.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a single value.
|
||||
*
|
||||
* @param value The string value.
|
||||
* @return The parsed value.
|
||||
*/
|
||||
private Object parseValue(String value) {
|
||||
if (value == null) return null;
|
||||
value = value.trim();
|
||||
if (type == Boolean.class) {
|
||||
if ("true".equalsIgnoreCase(value)) return Boolean.TRUE;
|
||||
if ("false".equalsIgnoreCase(value)) return Boolean.FALSE;
|
||||
return null;
|
||||
} else if (type == Double.class) {
|
||||
try {
|
||||
return Double.valueOf(Double.parseDouble(value));
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.mowesta.android.app.binding;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Represents a single measurement value.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasurementValue {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "MeasurementValue";
|
||||
|
||||
/**
|
||||
* The measurement type.
|
||||
*/
|
||||
private @NonNull
|
||||
MeasurementType type;
|
||||
|
||||
/**
|
||||
* The measurement value.
|
||||
*/
|
||||
private @Nullable
|
||||
String value;
|
||||
|
||||
/**
|
||||
* The extracted values.
|
||||
*/
|
||||
private @NonNull
|
||||
Object[] values;
|
||||
|
||||
public MeasurementValue(@NonNull MeasurementType type, @Nullable String value) {
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
this.values = parseValues();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to parse the value based on the type.
|
||||
*
|
||||
* @return The values.
|
||||
*/
|
||||
private @NonNull
|
||||
Object[] parseValues() {
|
||||
try {
|
||||
return type.getValues(value);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to parse " + type.name() + " from '" + value + "'.", e);
|
||||
return new Object[0];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the type.
|
||||
*
|
||||
* @return The type.
|
||||
*/
|
||||
@NonNull
|
||||
public MeasurementType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value(s).
|
||||
*
|
||||
* @return The values.
|
||||
*/
|
||||
@NonNull
|
||||
public Object[] getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this value has at
|
||||
* least one data item.
|
||||
*
|
||||
* @return True if the value has at least one data item..
|
||||
*/
|
||||
public boolean hasValue() {
|
||||
return values.length > 0;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import androidx.room.Ignore;
|
||||
import androidx.room.Index;
|
||||
import androidx.room.TypeConverters;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
@@ -48,7 +49,7 @@ public class Favorite {
|
||||
/**
|
||||
* The object mapper to serialize strings.
|
||||
*/
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper().configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
|
||||
|
||||
/**
|
||||
* The type of the favorite.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.mowesta.android.app.database;
|
||||
|
||||
import android.location.Location;
|
||||
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.room.Dao;
|
||||
import androidx.room.Delete;
|
||||
@@ -23,10 +25,20 @@ public interface FavoriteAccessor {
|
||||
|
||||
/**
|
||||
* Returns a live data list of active favorites.
|
||||
*
|
||||
* @return The list of active favorites.
|
||||
*/
|
||||
@Query("select * from favorite where not deleted order by position")
|
||||
LiveData<List<Favorite>> getActive();
|
||||
|
||||
/**
|
||||
* Returns the active locations that exhibit a certain type.
|
||||
*
|
||||
* @param type The location type.
|
||||
* @return The list of active favorites.
|
||||
*/
|
||||
@Query("select * from favorite where not deleted and type=:type order by position")
|
||||
List<Favorite> getActive(int type);
|
||||
|
||||
/**
|
||||
* returns the oldest entry in the database to determine whether
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
package com.mowesta.android.app.database;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.room.ColumnInfo;
|
||||
import androidx.room.Entity;
|
||||
import androidx.room.Index;
|
||||
import androidx.room.PrimaryKey;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A class to memorize the information about a widget.
|
||||
*/
|
||||
@Entity(tableName = "widget", indices = {
|
||||
@Index({"type", "ref"})
|
||||
})
|
||||
public class Widget {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "Widget";
|
||||
|
||||
/**
|
||||
* The object mapper to serialize strings.
|
||||
*/
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper().configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
|
||||
|
||||
/**
|
||||
* A constant to refer to an invalid type.
|
||||
*/
|
||||
public static final int TYPE_INVALID = 0;
|
||||
|
||||
/**
|
||||
* The widget type that shows a forecast. The data id will be a reference to a city.
|
||||
* The data will be the city and the content will be the forecast.
|
||||
*/
|
||||
public static final int TYPE_FORECAST = 1;
|
||||
|
||||
/**
|
||||
* The type that shows a measurement. The data id will be a reference to a device.
|
||||
* The data will be the device and the content will be the measurement.
|
||||
*/
|
||||
public static final int TYPE_MEASURE = 2;
|
||||
|
||||
/**
|
||||
* The type of the widget.
|
||||
*/
|
||||
@ColumnInfo(name = "type")
|
||||
@NonNull
|
||||
private int type;
|
||||
|
||||
/**
|
||||
* The id of the state of the widget.
|
||||
*/
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
@ColumnInfo(name = "id")
|
||||
private long id;
|
||||
|
||||
/**
|
||||
* The reference id of the widget. This
|
||||
* is the id assigned by the widget host.
|
||||
*/
|
||||
@ColumnInfo(name = "ref")
|
||||
private int reference;
|
||||
|
||||
/**
|
||||
* The id pointing to some data in the
|
||||
* mowesta backend. The type depends
|
||||
* on the widget type.
|
||||
*/
|
||||
@ColumnInfo(name = "dataId")
|
||||
private long dataId;
|
||||
|
||||
/**
|
||||
* The update timestamp of the last
|
||||
* data update.
|
||||
*/
|
||||
@ColumnInfo(name = "dataTime")
|
||||
private long dataTime;
|
||||
|
||||
/**
|
||||
* The widget data which depends on
|
||||
* the type.
|
||||
*/
|
||||
@ColumnInfo(name = "dataValue")
|
||||
private String dataValue;
|
||||
|
||||
/**
|
||||
* The update timestamp of the last
|
||||
* content update.
|
||||
*/
|
||||
@ColumnInfo(name = "contentTime")
|
||||
private long contentTime;
|
||||
|
||||
/**
|
||||
* The widget content which depends on
|
||||
* the type.
|
||||
*/
|
||||
@ColumnInfo(name = "contentValue")
|
||||
private String contentValue;
|
||||
|
||||
/**
|
||||
* A flag to store a temperature unit. True for
|
||||
* degree celsius, false for Fahrenheit.
|
||||
*/
|
||||
@ColumnInfo(name = "celsius")
|
||||
private boolean celsius;
|
||||
|
||||
/**
|
||||
* A flag to store a unit system. True for si
|
||||
* false for imperial.
|
||||
*/
|
||||
@ColumnInfo(name = "si")
|
||||
private boolean si;
|
||||
|
||||
/**
|
||||
* The color of the widget text.
|
||||
*/
|
||||
@ColumnInfo(name = "color")
|
||||
private int color;
|
||||
|
||||
/**
|
||||
* Returns the widget type.
|
||||
*
|
||||
* @return The widget type.
|
||||
*/
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the widget type.
|
||||
*
|
||||
* @param type The type.
|
||||
*/
|
||||
public void setType(int type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the widget id.
|
||||
*
|
||||
* @return The id.
|
||||
*/
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the widget id.
|
||||
*
|
||||
* @param id The widget id.
|
||||
*/
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the widget reference assigned
|
||||
* by the widget host.
|
||||
*
|
||||
* @return The reference.
|
||||
*/
|
||||
public int getReference() {
|
||||
return reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the widget reference assigned
|
||||
* by the host.
|
||||
*
|
||||
* @param reference The reference.
|
||||
*/
|
||||
public void setReference(int reference) {
|
||||
this.reference = reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data id pointing to the
|
||||
* server object.
|
||||
*
|
||||
* @return The data id.
|
||||
*/
|
||||
public long getDataId() {
|
||||
return dataId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the data id pointing to the server
|
||||
* object.
|
||||
*
|
||||
* @param dataId The data id.
|
||||
*/
|
||||
public void setDataId(long dataId) {
|
||||
this.dataId = dataId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data time.
|
||||
*
|
||||
* @return The data time.
|
||||
*/
|
||||
public long getDataTime() {
|
||||
return dataTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the data time.
|
||||
*
|
||||
* @param dataTime The data time.
|
||||
*/
|
||||
public void setDataTime(long dataTime) {
|
||||
this.dataTime = dataTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the data value.
|
||||
*
|
||||
* @return The data value.
|
||||
*/
|
||||
public String getDataValue() {
|
||||
return dataValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data value.
|
||||
*
|
||||
* @param dataValue The data value.
|
||||
*/
|
||||
public void setDataValue(String dataValue) {
|
||||
this.dataValue = dataValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content time.
|
||||
*
|
||||
* @return The content time.
|
||||
*/
|
||||
public long getContentTime() {
|
||||
return contentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the content time.
|
||||
*
|
||||
* @param contentTime The content time.
|
||||
*/
|
||||
public void setContentTime(long contentTime) {
|
||||
this.contentTime = contentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content value.
|
||||
*
|
||||
* @return The content value.
|
||||
*/
|
||||
public String getContentValue() {
|
||||
return contentValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the content value.
|
||||
*
|
||||
* @param contentValue The content value.
|
||||
*/
|
||||
public void setContentValue(String contentValue) {
|
||||
this.contentValue = contentValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes the content value as the specified type.
|
||||
*
|
||||
* @param type The type.
|
||||
* @param <T> The type.
|
||||
* @return The deserialized value or null, if deserialization fails.
|
||||
*/
|
||||
public <T> T getContent(Class<T> type) {
|
||||
try {
|
||||
String value = getContentValue();
|
||||
if (value == null) return null;
|
||||
else return MAPPER.readValue(value, type);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to deserialize widget content.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the content value by serializing the content as string.
|
||||
*
|
||||
* @param content The content to set.
|
||||
* @param <T> The type.
|
||||
*/
|
||||
public <T> void setContent(T content) {
|
||||
try {
|
||||
if (content == null) setContentValue(null);
|
||||
else setContentValue(MAPPER.writeValueAsString(content));
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to serialize widget content.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes the widget data from its string representation.
|
||||
*
|
||||
* @param type The type.
|
||||
* @param <T> The type.
|
||||
* @return The data or null, if something fails.
|
||||
*/
|
||||
public <T> T getData(Class<T> type) {
|
||||
try {
|
||||
String value = getDataValue();
|
||||
if (value == null) return null;
|
||||
else return MAPPER.readValue(value, type);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to deserialize widget data.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the widget data value by serializing the data.
|
||||
*
|
||||
* @param data The data.
|
||||
* @param <T> The type.
|
||||
*/
|
||||
public <T> void setData(T data) {
|
||||
try {
|
||||
if (data == null) setDataValue(null);
|
||||
else setDataValue(MAPPER.writeValueAsString(data));
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Failed to serialize widget data.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the temperature is shown as celsius.
|
||||
*
|
||||
* @return True if celsius, false for fahrenheit.
|
||||
*/
|
||||
public boolean isCelsius() {
|
||||
return celsius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the temperature is shown as celsius.
|
||||
*
|
||||
* @param celsius True if celsius, false for fahrenheit.
|
||||
*/
|
||||
public void setCelsius(boolean celsius) {
|
||||
this.celsius = celsius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the unit system. True for si, false
|
||||
* for imperial.
|
||||
*
|
||||
* @return True for si, false for imperial.
|
||||
*/
|
||||
public boolean isSi() {
|
||||
return si;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the unit system. True for si, false
|
||||
* for imperial.
|
||||
*
|
||||
* @param si True for si, false for imperial.
|
||||
*/
|
||||
public void setSi(boolean si) {
|
||||
this.si = si;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text color.
|
||||
*
|
||||
* @return The text color.
|
||||
*/
|
||||
public int getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the text color.
|
||||
*
|
||||
* @param color The text color.
|
||||
*/
|
||||
public void setColor(int color) {
|
||||
this.color = color;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.mowesta.android.app.database;
|
||||
|
||||
import androidx.room.Dao;
|
||||
import androidx.room.Insert;
|
||||
import androidx.room.Query;
|
||||
import androidx.room.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The widget access to manipulate the stored widget data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Dao
|
||||
public interface WidgetAccessor {
|
||||
|
||||
/**
|
||||
* Returns the widget with the specified id.
|
||||
*
|
||||
* @param id The id.
|
||||
* @return The widget.
|
||||
*/
|
||||
@Query("select * from widget where id=:id")
|
||||
Widget get(long id);
|
||||
|
||||
/**
|
||||
* Returns all widgets with the specified type and reference.
|
||||
*
|
||||
* @param type The type.
|
||||
* @param reference The reference.
|
||||
* @return The widgets matching the type and reference. There
|
||||
* should be only zero or one.
|
||||
*/
|
||||
@Query("select * from widget where type=:type and ref=:reference")
|
||||
List<Widget> get(int type, int reference);
|
||||
|
||||
/**
|
||||
* Inserts a widget into the databases.
|
||||
*
|
||||
* @param widget The widget to insert.
|
||||
*/
|
||||
@Insert
|
||||
void add(Widget widget);
|
||||
|
||||
/**
|
||||
* Updates the widget, if it exists.
|
||||
*
|
||||
* @param widget The widget to update.
|
||||
*/
|
||||
@Update
|
||||
void update(Widget widget);
|
||||
|
||||
/**
|
||||
* Deletes all widgets with the specified type and reference
|
||||
* from the database.
|
||||
*/
|
||||
@Query("delete from widget where type=:type and ref=:reference")
|
||||
void delete(int type, int reference);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.mowesta.android.app.database;
|
||||
|
||||
import android.graphics.Color;
|
||||
|
||||
import androidx.room.AutoMigration;
|
||||
import androidx.room.Database;
|
||||
import androidx.room.RoomDatabase;
|
||||
import androidx.room.migration.Migration;
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The database to store the widget information.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Database(entities = { Widget.class }, version = 4, exportSchema = true)
|
||||
|
||||
public abstract class WidgetDatabase extends RoomDatabase {
|
||||
|
||||
/**
|
||||
* Adds a non-null color column to the widget entry. This requires
|
||||
* us to copy the data, since sql lite cannot dynamically add or
|
||||
* remove constraints.
|
||||
*/
|
||||
private static final Migration MIGRATION_3_4 = new Migration(3, 4) {
|
||||
@Override
|
||||
public void migrate(SupportSQLiteDatabase database) {
|
||||
database.execSQL("DROP INDEX IF EXISTS `index_widget_type_ref`");
|
||||
database.execSQL("ALTER TABLE `widget` ADD COLUMN `color` INTEGER");
|
||||
database.execSQL("UPDATE `widget` SET `color` = ?", new Object[] { Color.rgb(255, 255, 255) } );
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `new_widget` (`type` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `ref` INTEGER NOT NULL, `dataId` INTEGER NOT NULL, `dataTime` INTEGER NOT NULL, `dataValue` TEXT, `contentTime` INTEGER NOT NULL, `contentValue` TEXT, `celsius` INTEGER NOT NULL, `si` INTEGER NOT NULL, `color` INTEGER NOT NULL)");
|
||||
database.execSQL("INSERT INTO `new_widget` SELECT * FROM `widget`");
|
||||
database.execSQL("DROP TABLE `widget`");
|
||||
database.execSQL("ALTER TABLE `new_widget` RENAME TO `widget`");
|
||||
database.execSQL("CREATE INDEX IF NOT EXISTS `index_widget_type_ref` ON `widget` (`type`, `ref`)");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an array with all migrations.
|
||||
*
|
||||
* @return The array with migrations.
|
||||
*/
|
||||
public static Migration[] getMigrations() {
|
||||
return new Migration[] {
|
||||
MIGRATION_3_4
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the widget accessor.
|
||||
*
|
||||
* @return The widget accessor.
|
||||
*/
|
||||
public abstract WidgetAccessor getAccessor();
|
||||
|
||||
|
||||
}
|
||||
+31
-27
@@ -5,11 +5,14 @@ import android.os.Bundle;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuInflater;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
@@ -30,22 +33,23 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
|
||||
* A preference listener that is running as long as we are resumed.
|
||||
*/
|
||||
private SharedPreferences.OnSharedPreferenceChangeListener unitListener = (prefs, key) -> {
|
||||
if (MowestaSettings.TEMPERATURE_CELSIUS.equals(key)) onUnitChanged();
|
||||
if (MowestaSettings.TEMPERATURE_UNIT.equals(key) || MowestaSettings.UNIT_SYSTEM.equals(key)) {
|
||||
onRefreshDiagram();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
settings = new MowestaSettings(getActivity().getApplication());
|
||||
settings = ((IApp)getContext().getApplicationContext()).getSettings();
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
settings.getPreferences().registerOnSharedPreferenceChangeListener(unitListener);
|
||||
onUnitChanged();
|
||||
onRefreshDiagram();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -58,32 +62,32 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
|
||||
* Called whenever the unit changes. Subclasses may overwrite this,
|
||||
* but should call through to super.
|
||||
*/
|
||||
public void onUnitChanged() {
|
||||
getActivity().invalidateOptionsMenu();
|
||||
}
|
||||
public abstract void onRefreshDiagram();
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_unit, menu);
|
||||
boolean celsius = settings.isTemperatureCelsius();
|
||||
menu.findItem(R.id.unit_celsius).setVisible(celsius);
|
||||
menu.findItem(R.id.unit_fahrenheit).setVisible(!celsius);
|
||||
}
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
inflater.inflate(R.menu.menu_unit, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.unit_fahrenheit:
|
||||
settings.setTemperatureCelsius(true);
|
||||
return true;
|
||||
case R.id.unit_celsius:
|
||||
settings.setTemperatureCelsius(false);
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem item) {
|
||||
int itemId = item.getItemId();
|
||||
if (itemId == R.id.action_unit_system) {
|
||||
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
|
||||
system.show(getChildFragmentManager(), "system");
|
||||
return true;
|
||||
} else if (itemId == R.id.action_temperature_unit) {
|
||||
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
|
||||
unit.show(getChildFragmentManager(), "unit");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+39
-43
@@ -11,6 +11,7 @@ import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
@@ -44,12 +45,6 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
|
||||
*/
|
||||
protected abstract AbstractPlaceViewModel getPlaceViewModel();
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
@@ -58,45 +53,46 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
|
||||
model.getCoordinate().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
|
||||
model.getFavorite().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
|
||||
model.getWikipedia().observe(getViewLifecycleOwner() ,(v) -> getActivity().invalidateOptionsMenu());
|
||||
}
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
inflater.inflate(R.menu.menu_place, menu);
|
||||
AbstractPlaceViewModel model = getPlaceViewModel();
|
||||
Boolean favorite = model.getFavorite().getValue();
|
||||
if (favorite == null || favorite) {
|
||||
menu.removeItem(R.id.action_favorite_add);
|
||||
}
|
||||
if (favorite == null || !favorite) {
|
||||
menu.removeItem(R.id.action_favorite_remove);
|
||||
}
|
||||
if (model.getWikipedia().getValue() == null) {
|
||||
menu.removeItem(R.id.action_wikipedia);
|
||||
}
|
||||
if (model.getCoordinate().getValue() == null) {
|
||||
menu.removeItem(R.id.action_google_maps);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_place, menu);
|
||||
AbstractPlaceViewModel model = getPlaceViewModel();
|
||||
Boolean favorite = model.getFavorite().getValue();
|
||||
if (favorite == null || favorite) {
|
||||
menu.removeItem(R.id.action_favorite_add);
|
||||
}
|
||||
if (favorite == null || !favorite) {
|
||||
menu.removeItem(R.id.action_favorite_remove);
|
||||
}
|
||||
if (model.getWikipedia().getValue() == null) {
|
||||
menu.removeItem(R.id.action_wikipedia);
|
||||
}
|
||||
if (model.getCoordinate().getValue() == null) {
|
||||
menu.removeItem(R.id.action_google_maps);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem item) {
|
||||
int itemId = item.getItemId();
|
||||
if (itemId == R.id.action_favorite_add) {
|
||||
getPlaceViewModel().addFavorite();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_favorite_remove) {
|
||||
getPlaceViewModel().removeFavorite();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_wikipedia) {
|
||||
openWikipedia();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_google_maps) {
|
||||
openGoogleMaps();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_favorite_add:
|
||||
getPlaceViewModel().addFavorite();
|
||||
return true;
|
||||
case R.id.action_favorite_remove:
|
||||
getPlaceViewModel().removeFavorite();
|
||||
return true;
|
||||
case R.id.action_wikipedia:
|
||||
openWikipedia();
|
||||
return true;
|
||||
case R.id.action_google_maps:
|
||||
openGoogleMaps();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
|
||||
import com.google.android.material.bottomsheet.BottomSheetBehavior;
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog;
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.DialogAdvertiseBinding;
|
||||
import com.mowesta.android.app.model.AdvertiseViewModel;
|
||||
|
||||
public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
|
||||
|
||||
public static final String KEY_ADVERTISEMENT = "advertisement";
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
Dialog dialog = super.onCreateDialog(savedInstanceState);
|
||||
|
||||
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
|
||||
@Override
|
||||
public void onShow(DialogInterface dialog) {
|
||||
BottomSheetDialog d = (BottomSheetDialog) dialog;
|
||||
FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
|
||||
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
|
||||
}
|
||||
});
|
||||
return dialog;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
DialogAdvertiseBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_advertise, container, false);
|
||||
AdvertiseViewModel model = new ViewModelProvider(this).get(AdvertiseViewModel.class);
|
||||
binding.setModel(model);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.videoView.setPlayer(model.getExoPlayer());
|
||||
binding.videoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
|
||||
model.getClose().observe(getViewLifecycleOwner(), (v) -> { if (v) this.dismiss(); } );
|
||||
model.getOpen().observe(getViewLifecycleOwner(), (v) -> {
|
||||
if (v) {
|
||||
String url = "https://www.mowesta.com/2022/05/23/fair-experiment-bei-das-fest-in-karlsruhe/";
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(url));
|
||||
try {
|
||||
startActivity(i);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Snackbar.make(getView(), R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
model.getOpen().setValue(Boolean.FALSE);
|
||||
}
|
||||
});
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
|
||||
public boolean shouldShow(Context context) {
|
||||
long time = System.currentTimeMillis();
|
||||
if (time > 1658700000000l) return false;
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
long last = prefs.getLong(KEY_ADVERTISEMENT, 0);
|
||||
return (time - last > 7 * 24* 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDismiss(@NonNull DialogInterface dialog) {
|
||||
super.onDismiss(dialog);
|
||||
Context context = getActivity();
|
||||
if (context != null) {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
SharedPreferences.Editor e = prefs.edit();
|
||||
e.putLong(KEY_ADVERTISEMENT, System.currentTimeMillis());
|
||||
e.apply();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.content.res.Configuration;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -18,6 +19,9 @@ import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.CitiesViewModel;
|
||||
import com.mowesta.android.app.model.StateViewModel;
|
||||
import com.mowesta.android.app.util.TabletUtil;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
||||
/**
|
||||
@@ -26,6 +30,7 @@ import com.mowesta.android.app.model.StateViewModel;
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CitiesFragment extends AbstractNetworkFragment {
|
||||
private RecyclerView recyclerView;
|
||||
|
||||
@Override
|
||||
protected AbstractNetworkViewModel getNetworkViewModel() {
|
||||
@@ -38,10 +43,27 @@ public class CitiesFragment extends AbstractNetworkFragment {
|
||||
return inflater.inflate(R.layout.fragment_cities, container, false);
|
||||
}
|
||||
|
||||
private void applyGridWidth() {
|
||||
if (!TabletUtil.isTablet(requireContext())) {
|
||||
return;
|
||||
}
|
||||
|
||||
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
|
||||
TabletUtil.setGridLayout(recyclerView, width);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(@NotNull Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
applyGridWidth();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
RecyclerView recyclerView = view.findViewById(R.id.recycler);
|
||||
recyclerView = view.findViewById(R.id.recycler);
|
||||
applyGridWidth();
|
||||
|
||||
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
CityEntryPagedListAdapter adapter = new CityEntryPagedListAdapter(getViewLifecycleOwner(), (city) -> {
|
||||
if (city != null) {
|
||||
|
||||
+41
-20
@@ -2,6 +2,7 @@ package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
@@ -12,6 +13,7 @@ import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.recyclerview.widget.GridLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter;
|
||||
@@ -24,6 +26,7 @@ import com.mowesta.android.app.databinding.ViewSummaryBinding;
|
||||
import com.mowesta.android.app.databinding.ViewConditionBinding;
|
||||
import com.mowesta.android.app.model.CityViewModel;
|
||||
import com.mowesta.android.app.model.ConditionViewModel;
|
||||
import com.mowesta.android.app.model.CustomizeViewModel;
|
||||
import com.mowesta.android.app.model.SummaryViewModel;
|
||||
import com.mowesta.android.app.util.TabletUtil;
|
||||
import com.mowesta.android.feign.model.WeatherCondition;
|
||||
@@ -51,29 +54,32 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
ViewPager2 pager = view.findViewById(R.id.pager);
|
||||
CityViewModel model = getCityViewModel();
|
||||
pager.setAdapter(new ForecastAdapter(this));
|
||||
model.getNavigation().observe(getViewLifecycleOwner(), (request) -> {
|
||||
if (request != null) {
|
||||
switch (request.getType()) {
|
||||
case DAY:
|
||||
pager.setCurrentItem(0, true);
|
||||
break;
|
||||
case TIME:
|
||||
pager.setCurrentItem(1, true);
|
||||
break;
|
||||
case HOUR:
|
||||
case TIME:
|
||||
pager.setCurrentItem(2, true);
|
||||
break;
|
||||
case HOUR:
|
||||
pager.setCurrentItem(3, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
pager.setAdapter(new ForecastAdapter(this));
|
||||
TabLayout tabs = view.findViewById(R.id.tabs);
|
||||
new TabLayoutMediator(tabs, pager, (tab, position) -> {
|
||||
switch (position) {
|
||||
case 0:
|
||||
tab.setText(R.string.city_info_day);
|
||||
tab.setText(R.string.city_info_gradient);
|
||||
break;
|
||||
case 1:
|
||||
tab.setText(R.string.city_info_day);
|
||||
break;
|
||||
case 2:
|
||||
tab.setText(R.string.city_info_time);
|
||||
break;
|
||||
default:
|
||||
@@ -83,6 +89,7 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
}).attach();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The adapter for the pager that displays the different time granularities.
|
||||
*
|
||||
@@ -98,16 +105,20 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
@NonNull
|
||||
@Override
|
||||
public Fragment createFragment(int position) {
|
||||
ForecastRecyclerFragment fragment = new ForecastRecyclerFragment();
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("page", position);
|
||||
fragment.setArguments(bundle);
|
||||
return fragment;
|
||||
if (position == 0) {
|
||||
return new CityGradientFragment();
|
||||
} else {
|
||||
ForecastRecyclerFragment fragment = new ForecastRecyclerFragment();
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("page", position - 1);
|
||||
fragment.setArguments(bundle);
|
||||
return fragment;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return 3;
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +132,7 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
public static class ForecastRecyclerFragment extends CityFragment.ChildFragment {
|
||||
|
||||
/** A handler to post updates. */
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
@@ -146,14 +157,14 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
for (int i = 0; i < models.size(); i++) {
|
||||
SummaryViewModel s = models.get(i);
|
||||
if (s.getFirstCondition() != null && s.getFirstCondition().getTime() == time) {
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.NavigationRequest.ListType.TIME, i));
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.ForecastType.TIME, i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
model.getNavigation().observe(getViewLifecycleOwner(), (request) -> {
|
||||
if (request == null) return;
|
||||
if (request.getType() == CityViewModel.NavigationRequest.ListType.DAY) {
|
||||
if (request.getType() == CityViewModel.ForecastType.DAY) {
|
||||
recyclerView.post(() -> {
|
||||
scrollRecyclerViewToPosition(recyclerView, request.getPosition());
|
||||
model.getNavigation().setValue(null);
|
||||
@@ -171,14 +182,14 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
ConditionViewModel c = models.get(i);
|
||||
WeatherCondition wc = c.getCondition().getValue();
|
||||
if (wc != null && wc.getTime() == time) {
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.NavigationRequest.ListType.HOUR, i));
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.ForecastType.HOUR, i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
model.getNavigation().observe(getViewLifecycleOwner(), (request) -> {
|
||||
if (request == null) return;
|
||||
if (request.getType() == CityViewModel.NavigationRequest.ListType.TIME) {
|
||||
if (request.getType() == CityViewModel.ForecastType.TIME) {
|
||||
recyclerView.post(() -> {
|
||||
scrollRecyclerViewToPosition(recyclerView, request.getPosition());
|
||||
model.getNavigation().setValue(null);
|
||||
@@ -196,14 +207,14 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
SummaryViewModel s = models.get(i);
|
||||
if (s.getFirstCondition() != null && s.getLastCondition() != null
|
||||
&& s.getLastCondition().getTime() >= time && s.getFirstCondition().getTime() <= time) {
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.NavigationRequest.ListType.DAY, i));
|
||||
model.getNavigation().setValue(new CityViewModel.NavigationRequest(CityViewModel.ForecastType.DAY, i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
model.getNavigation().observe(getViewLifecycleOwner(), (request) -> {
|
||||
if (request == null) return;
|
||||
if (request.getType() == CityViewModel.NavigationRequest.ListType.HOUR) {
|
||||
if (request.getType() == CityViewModel.ForecastType.HOUR) {
|
||||
recyclerView.post(() -> {
|
||||
scrollRecyclerViewToPosition(recyclerView, request.getPosition());
|
||||
model.getNavigation().setValue(null);
|
||||
@@ -212,6 +223,17 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
});
|
||||
break;
|
||||
}
|
||||
// Customization
|
||||
CustomizeViewModel customize = new ViewModelProvider(getActivity()).get(CustomizeViewModel.class);
|
||||
customize.getTemperatureUnit().observe(getViewLifecycleOwner(), (v) -> updateRecycler(recyclerView) );
|
||||
customize.getUnitSystem().observe(getViewLifecycleOwner(), (v) -> updateRecycler(recyclerView) );
|
||||
}
|
||||
|
||||
private void updateRecycler(RecyclerView view) {
|
||||
int count = view.getAdapter().getItemCount();
|
||||
if (count > 0) {
|
||||
view.getAdapter().notifyItemRangeChanged(0, count);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -413,5 +435,4 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
@@ -25,7 +26,7 @@ import com.locoslab.android.leafless.MapView;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentCityBinding;
|
||||
import com.mowesta.android.app.model.AbstractPlaceViewModel;
|
||||
import com.mowesta.android.app.model.BindingTransforms;
|
||||
import com.mowesta.android.app.binding.BindingTransforms;
|
||||
import com.mowesta.android.app.model.CityViewModel;
|
||||
import com.mowesta.android.app.util.MapViewUtil;
|
||||
|
||||
@@ -71,32 +72,6 @@ public class CityFragment extends AbstractPlaceFragment {
|
||||
return getView().findViewById(R.id.bottom_navigation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_customize, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_customize:
|
||||
getChildFragmentManager()
|
||||
.beginTransaction()
|
||||
.add(new CustomizeDialogFragment(), "customize")
|
||||
.commit();
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
@@ -128,5 +103,26 @@ public class CityFragment extends AbstractPlaceFragment {
|
||||
return root;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
inflater.inflate(R.menu.menu_customize, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem item) {
|
||||
if (item.getItemId() == R.id.action_customize) {
|
||||
getChildFragmentManager()
|
||||
.beginTransaction()
|
||||
.add(new CustomizeDialogFragment(), "customize")
|
||||
.commit();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.constraintlayout.widget.ConstraintLayout;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.viewpager2.widget.ViewPager2;
|
||||
|
||||
import com.google.android.material.appbar.AppBarLayout;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentGradientBinding;
|
||||
import com.mowesta.android.app.model.CustomizeViewModel;
|
||||
import com.mowesta.android.app.util.DateFormatter;
|
||||
import com.mowesta.android.app.util.TimeUtils;
|
||||
import com.mowesta.android.app.view.DataView;
|
||||
import com.mowesta.android.app.view.TimeView;
|
||||
import com.mowesta.android.app.view.color.CloudDepthColorScheme;
|
||||
import com.mowesta.android.app.view.color.HumidityColorScheme;
|
||||
import com.mowesta.android.app.view.color.PrecipitationColorScheme;
|
||||
import com.mowesta.android.app.view.color.PressureColorScheme;
|
||||
import com.mowesta.android.app.view.color.ScientificTemperatureColorScheme;
|
||||
import com.mowesta.android.app.view.color.WhiteCloudColorScheme;
|
||||
import com.mowesta.android.feign.model.WeatherCondition;
|
||||
|
||||
/**
|
||||
* The fragment to show the overview as a bunch of gradients.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CityGradientFragment extends CityFragment.ChildFragment {
|
||||
|
||||
/**
|
||||
* The timeout after which we reset the view.
|
||||
*/
|
||||
private static final int TIMEOUT_REMOVER = 10000;
|
||||
|
||||
/**
|
||||
* The view binding.
|
||||
*/
|
||||
private FragmentGradientBinding binding;
|
||||
|
||||
/**
|
||||
* The time utilities.
|
||||
*/
|
||||
private TimeUtils timeUtils = new TimeUtils(System.currentTimeMillis(), null);
|
||||
|
||||
/**
|
||||
* The date formatter.
|
||||
*/
|
||||
private DateFormatter dateFormatter;
|
||||
|
||||
/**
|
||||
* The handler to post the removal of
|
||||
*/
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The animator for the progress bar.
|
||||
*/
|
||||
private ValueAnimator animator;
|
||||
|
||||
/**
|
||||
* The weather condition to display as text.
|
||||
*/
|
||||
private WeatherCondition condition = new WeatherCondition();
|
||||
|
||||
private boolean closed = false;
|
||||
|
||||
private Runnable remover = () -> {
|
||||
updateSelection(null);
|
||||
animator.cancel();
|
||||
binding.gradientText.setVisibility(View.GONE);
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
dateFormatter = new DateFormatter(getContext());
|
||||
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_gradient, container, false);
|
||||
// this is quite ugly, but we need to disable the view pager and collapse the toolbar
|
||||
binding.gradientProgress1.setMax(TIMEOUT_REMOVER);
|
||||
binding.gradientProgress2.setMax(TIMEOUT_REMOVER);
|
||||
animator = ValueAnimator.ofInt(TIMEOUT_REMOVER, 0);
|
||||
animator.setInterpolator(new LinearInterpolator());
|
||||
animator.setDuration(TIMEOUT_REMOVER);
|
||||
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation){
|
||||
int value = (Integer)animation.getAnimatedValue();
|
||||
binding.gradientProgress1.setProgress(value);
|
||||
binding.gradientProgress2.setProgress(value);
|
||||
binding.gradientText.setAlpha(Math.min(1, Math.max(0, value / 1000f)));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.gradientText.setVisibility(View.GONE);
|
||||
binding.gradientTemperature.setColorScheme(new ScientificTemperatureColorScheme());
|
||||
binding.gradientCloud.setColorScheme(new WhiteCloudColorScheme());
|
||||
binding.gradientCloud.setSecondaryColorScheme(new CloudDepthColorScheme());
|
||||
binding.gradientPreciptiation.setColorScheme(new PrecipitationColorScheme());
|
||||
binding.gradientHumidity.setColorScheme(new HumidityColorScheme());
|
||||
getCityViewModel().getHour().observe(getViewLifecycleOwner(), (list) -> {
|
||||
if (list == null) return;
|
||||
int housrs = 0;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
housrs += list.get(i).getCondition().getValue().getDuration();
|
||||
}
|
||||
Double[] temp = new Double[housrs];
|
||||
Double[] cloud = new Double[housrs];
|
||||
Double[] depth = new Double[housrs];
|
||||
Double[] prec = new Double[housrs];
|
||||
Double[] pres = new Double[housrs];
|
||||
Double[] wind = new Double[housrs];
|
||||
Double[] hum = new Double[housrs];
|
||||
Long[] hours = new Long[housrs];
|
||||
int index = 0;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
WeatherCondition wc = list.get(i).getCondition().getValue();
|
||||
for (int j = 0; j < wc.getDuration(); j++) {
|
||||
temp[index] = wc.getTemperature();
|
||||
cloud[index] = wc.getCloudCoverage();
|
||||
prec[index] = wc.getPrecipitation();
|
||||
pres[index] = wc.getPressure();
|
||||
depth[index] = wc.getCloudDepth();
|
||||
wind[index] = wc.getWindSpeed();
|
||||
hum[index] = wc.getHumidity();
|
||||
hours[index] = wc.getTime() + j * 3600000;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
binding.gradientCloud.setSecondaryData(depth);
|
||||
binding.gradientTemperature.setData(temp);
|
||||
binding.gradientPressure.setData(pres);
|
||||
binding.gradientCloud.setData(cloud);
|
||||
binding.gradientPreciptiation.setData(prec);
|
||||
binding.gradientWindSpeed.setData(wind);
|
||||
binding.gradientHumidity.setData(hum);
|
||||
binding.gradientTouch.setData(hours);
|
||||
});
|
||||
getCityViewModel().getForecast().observe(getViewLifecycleOwner(), (forecast) -> {
|
||||
if (forecast != null) {
|
||||
// 1013,25 hPa * [ 1 − 6,5 * Höhe / (288150 m) ]5,255
|
||||
double avg = 1013.25 * Math.pow(1 - 6.5 * forecast.getSurfaceHeight() / 288150.0, 5.255);
|
||||
binding.gradientPressure.setColorScheme(new PressureColorScheme(avg, avg - 20, avg + 10));
|
||||
}
|
||||
});
|
||||
getCityViewModel().getCity().observe(getViewLifecycleOwner(), (city) -> {
|
||||
if (city != null) {
|
||||
binding.gradientTouch.setTimezone(city.getTimezone());
|
||||
timeUtils = new TimeUtils(System.currentTimeMillis(), city.getTimezone());
|
||||
}
|
||||
});
|
||||
// observe changes to the settings that affect us
|
||||
CustomizeViewModel customizeViewModel = new ViewModelProvider(this).get(CustomizeViewModel.class);
|
||||
customizeViewModel.getTemperatureUnit().observe(getViewLifecycleOwner(), (u)-> {
|
||||
Float selection = binding.gradientTouch.getSelection();
|
||||
if (selection != null) updateCondition(selection);
|
||||
});
|
||||
customizeViewModel.getUnitSystem().observe(getViewLifecycleOwner(), (s) -> {
|
||||
Float selection = binding.gradientTouch.getSelection();
|
||||
if (selection != null) updateCondition(selection);
|
||||
});
|
||||
|
||||
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
private boolean hasData() {
|
||||
return binding.gradientTouch.getData() != null && binding.gradientTouch.getData().length > 0;
|
||||
}
|
||||
|
||||
private void updateSelection(Float selection) {
|
||||
binding.gradientTemperature.setSelection(selection);
|
||||
binding.gradientWindSpeed.setSelection(selection);
|
||||
binding.gradientPreciptiation.setSelection(selection);
|
||||
binding.gradientHumidity.setSelection(selection);
|
||||
binding.gradientPressure.setSelection(selection);
|
||||
binding.gradientCloud.setSelection(selection);
|
||||
binding.gradientTouch.setSelection(selection);
|
||||
}
|
||||
|
||||
private void updateCondition(float selection) {
|
||||
long time = binding.gradientTouch.getDataAt(selection);
|
||||
condition.setTime(time);
|
||||
condition.setWindSpeed(binding.gradientWindSpeed.getDataAt(selection));
|
||||
condition.setPrecipitation(binding.gradientPreciptiation.getDataAt(selection));
|
||||
condition.setHumidity(binding.gradientHumidity.getDataAt(selection));
|
||||
condition.setPressure(binding.gradientPressure.getDataAt(selection));
|
||||
condition.setCloudCoverage(binding.gradientCloud.getDataAt(selection));
|
||||
condition.setTemperature(binding.gradientTemperature.getDataAt(selection));
|
||||
String day = timeUtils.getDayName(getContext(), time);
|
||||
String hour = dateFormatter.asTime(time, binding.gradientTouch.getTimezone());
|
||||
binding.gradientTime.setText(getString(R.string.format_two_parts, day, hour));
|
||||
binding.setModel(condition);
|
||||
}
|
||||
|
||||
private void updateGuide(float relative) {
|
||||
float px = 64 * getResources().getDisplayMetrics().density;
|
||||
float max = 128 * getResources().getDisplayMetrics().density;
|
||||
int size = binding.gradientTouch.getDirection() == DataView.Direction.HORIZONTAL ?
|
||||
binding.gradientConstraint.getWidth():binding.gradientConstraint.getHeight();
|
||||
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams)binding.gradientText.getLayoutParams();
|
||||
float percent = size == 0 ? 0 : px / size;
|
||||
float delta = size == 0 ? 0 : max / size;
|
||||
if (binding.gradientTouch.getDirection() == DataView.Direction.VERTICAL) {
|
||||
if (relative - delta < 0) {
|
||||
binding.guideGradient.setGuidelinePercent(relative + 2 * percent);
|
||||
params.bottomToTop = -1;
|
||||
params.topToBottom = R.id.guide_gradient;
|
||||
} else {
|
||||
binding.guideGradient.setGuidelinePercent(relative - percent);
|
||||
params.topToBottom = -1;
|
||||
params.bottomToTop = R.id.guide_gradient;
|
||||
}
|
||||
|
||||
} else {
|
||||
if (relative > 0.5) {
|
||||
binding.guideGradient.setGuidelinePercent(relative - percent);
|
||||
params.leftToLeft = -1;
|
||||
params.rightToRight = R.id.guide_gradient;
|
||||
} else {
|
||||
binding.guideGradient.setGuidelinePercent(relative + percent);
|
||||
params.leftToLeft = R.id.guide_gradient;
|
||||
params.rightToRight = -1;
|
||||
}
|
||||
}
|
||||
binding.gradientText.setLayoutParams(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
handler.removeCallbacks(remover);
|
||||
remover.run();
|
||||
binding.gradientScroll.setOnTouchListener(null);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
|
||||
ViewPager2 pager = getActivity().findViewById(R.id.pager);
|
||||
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
|
||||
@Override
|
||||
public void onSlide(float relative) {
|
||||
if (!hasData()) return;
|
||||
animator.cancel();
|
||||
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
|
||||
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
|
||||
binding.gradientText.setAlpha(1);
|
||||
handler.removeCallbacks(remover);
|
||||
if (!closed) {
|
||||
if (layout != null)
|
||||
layout.setExpanded(false, true);
|
||||
closed = true;
|
||||
}
|
||||
if (pager != null)
|
||||
pager.setUserInputEnabled(false);
|
||||
updateSelection(relative);
|
||||
updateCondition(relative);
|
||||
binding.gradientText.setVisibility(View.VISIBLE);
|
||||
updateGuide(relative);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSlideEnd() {
|
||||
if (pager != null)
|
||||
pager.setUserInputEnabled(true);
|
||||
closed = false;
|
||||
animator.start();
|
||||
handler.postDelayed(remover, TIMEOUT_REMOVER);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
binding.gradientTouch.setOnTouchListener(null);
|
||||
super.onDestroyView();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import com.locoslab.android.leafless.MapView;
|
||||
import com.locoslab.android.leafless.polyline.Polyline;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentCityInfoBinding;
|
||||
import com.mowesta.android.app.model.BindingTransforms;
|
||||
import com.mowesta.android.app.binding.BindingTransforms;
|
||||
import com.mowesta.android.app.model.CityViewModel;
|
||||
import com.mowesta.android.app.model.ConditionViewModel;
|
||||
import com.mowesta.android.app.util.MapViewUtil;
|
||||
@@ -45,13 +45,7 @@ public class CityInfoFragment extends CityFragment.ChildFragment {
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentCityInfoBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_city_info, container, false);
|
||||
MapView mapView = binding.getRoot().findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
// reduce brightness of map (technically, we should generate a night mode in leafless but this needs to be fixed in the library)
|
||||
if (getResources().getBoolean(R.bool.dark_mode)) {
|
||||
mapView.setAlpha(0.5f);
|
||||
} else {
|
||||
mapView.setAlpha(1f);
|
||||
}
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
CityViewModel model = new ViewModelProvider(getParentFragment().getParentFragment()).get(CityViewModel.class);
|
||||
ConditionViewModel condition = new ViewModelProvider(this).get(ConditionViewModel.class);
|
||||
Runnable updateCondition = () -> {
|
||||
@@ -83,6 +77,8 @@ public class CityInfoFragment extends CityFragment.ChildFragment {
|
||||
model.getBoundary().observe(getViewLifecycleOwner(), (b) -> updateMap.run());
|
||||
binding.setModel(model);
|
||||
binding.setCondition(condition);
|
||||
condition.getUnitSystem().observe(getViewLifecycleOwner(), (s) -> updateCondition.run());
|
||||
condition.getTemperatureUnit().observe(getViewLifecycleOwner(), (s) -> updateCondition.run());
|
||||
NavController appController = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
binding.setStationListener(new CityViewModel.OnStationSelectedListener() {
|
||||
@Override
|
||||
@@ -94,10 +90,8 @@ public class CityInfoFragment extends CityFragment.ChildFragment {
|
||||
appController.navigate(R.id.destination_station, bundle, opts.build());
|
||||
}
|
||||
});
|
||||
System.out.println("XXXX");
|
||||
NavController cityController = Navigation.findNavController(getActivity(), R.id.navigation_city);
|
||||
binding.setConditionListener(m -> {
|
||||
System.out.println("here");
|
||||
NavController cityController = Navigation.findNavController(getActivity(), R.id.navigation_city);
|
||||
cityController.navigate(R.id.destination_city_forecast);
|
||||
});
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.Observer;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.Navigation;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
@@ -25,6 +26,7 @@ import com.mowesta.android.app.model.CityViewModel;
|
||||
import com.mowesta.android.app.model.VideoViewModel;
|
||||
import com.mowesta.android.app.util.TabletUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -34,6 +36,11 @@ import java.util.List;
|
||||
*/
|
||||
public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
|
||||
/**
|
||||
* The mediator to update the tabs.
|
||||
*/
|
||||
private TabLayoutMediator mediator;
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
@@ -44,10 +51,29 @@ public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
ViewPager2 pager = view.findViewById(R.id.pager);
|
||||
pager.setAdapter(new VideoAdpter(this));
|
||||
TabLayout tabs = view.findViewById(R.id.tabs);
|
||||
new TabLayoutMediator(tabs, pager, (tab, position) -> {
|
||||
switch (position) {
|
||||
List<Integer> pages = new ArrayList<>();
|
||||
CityViewModel model = getCityViewModel();
|
||||
pager.setAdapter(new VideoAdpter(this, pages));
|
||||
updateMediator(tabs, pager, pages);
|
||||
Observer<List<VideoViewModel>> videoObserver = (v) -> {
|
||||
pages.clear();
|
||||
if (model.getIconGlobal().getValue().size() > 0) pages.add(0, 0);
|
||||
if (model.getIconEurope().getValue().size() > 0) pages.add(0, 1);
|
||||
if (model.getCosmoEurope().getValue().size() > 0) pages.add(0, 2);
|
||||
pager.setAdapter(new VideoAdpter(this, pages));
|
||||
updateMediator(tabs, pager, pages);
|
||||
};
|
||||
model.getCosmoEurope().observe(getViewLifecycleOwner(), videoObserver);
|
||||
model.getIconEurope().observe(getViewLifecycleOwner(), videoObserver);
|
||||
model.getIconGlobal().observe(getViewLifecycleOwner(), videoObserver);
|
||||
}
|
||||
|
||||
private void updateMediator(TabLayout tabs, ViewPager2 pager, List<Integer> pages) {
|
||||
if (mediator != null && mediator.isAttached()) mediator.detach();
|
||||
mediator = new TabLayoutMediator(tabs, pager, (tab, position) -> {
|
||||
int page = pages.get(position);
|
||||
switch (page) {
|
||||
case 0:
|
||||
tab.setText(R.string.video_source_icon_global);
|
||||
break;
|
||||
@@ -58,7 +84,8 @@ public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
tab.setText(R.string.video_source_cosmo_europe);
|
||||
break;
|
||||
}
|
||||
}).attach();
|
||||
});
|
||||
mediator.attach();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,8 +95,11 @@ public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
*/
|
||||
private static class VideoAdpter extends FragmentStateAdapter {
|
||||
|
||||
public VideoAdpter(@NonNull Fragment fragment) {
|
||||
private List<Integer> pages;
|
||||
|
||||
public VideoAdpter(@NonNull Fragment fragment, @NonNull List<Integer> pages) {
|
||||
super(fragment);
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -77,14 +107,14 @@ public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
public Fragment createFragment(int position) {
|
||||
VideoRecyclerFragment fragment = new VideoRecyclerFragment();
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("page", position);
|
||||
bundle.putInt("page", pages.get(position));
|
||||
fragment.setArguments(bundle);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return 3;
|
||||
return pages.size();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +136,7 @@ public class CityVideoFragment extends CityFragment.ChildFragment {
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
RecyclerView recyclerView = getView().findViewById(R.id.recycler);
|
||||
TabletUtil.setGridLayout(recyclerView, 600);
|
||||
TabletUtil.setGridLayout(recyclerView, 400);
|
||||
CityViewModel model = getCityViewModel();
|
||||
int page = getArguments().getInt("page");
|
||||
VideoViewModel.OnVideoSelectedListener listener = (video) -> {
|
||||
|
||||
@@ -23,6 +23,7 @@ import androidx.fragment.app.Fragment;
|
||||
import androidx.navigation.Navigation;
|
||||
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentCollectionBinding;
|
||||
@@ -61,7 +62,7 @@ public class CollectionFragment extends Fragment {
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
this.settings = new MowestaSettings(getActivity().getApplication());
|
||||
this.settings = ((IApp)getContext().getApplicationContext()).getSettings();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -87,9 +88,11 @@ public class CollectionFragment extends Fragment {
|
||||
// add a funky animation
|
||||
if (savedInstanceState == null) {
|
||||
List<View> views = new ArrayList<>();
|
||||
views.add(binding.collectionNotePermission);
|
||||
views.add(binding.collectionNoteLocation);
|
||||
views.add(binding.collectionNoteData);
|
||||
views.add(binding.collectionNoteEnable);
|
||||
views.add(binding.privacyMeasureSwitch);
|
||||
views.add(binding.collectionNotePermission);
|
||||
views.add(binding.buttonContinue);
|
||||
AnimatorSet set = new AnimatorSet();
|
||||
ObjectAnimator first = ObjectAnimator.ofFloat(binding.logoSun, "translationY", DisplayUtils.dpToPixels(getContext(), 90), 0f);
|
||||
@@ -109,7 +112,7 @@ public class CollectionFragment extends Fragment {
|
||||
}
|
||||
set.start();
|
||||
}
|
||||
return binding.getRoot();
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.DialogColorBinding;
|
||||
import com.mowesta.android.app.model.ColorViewModel;
|
||||
|
||||
/**
|
||||
* A dialog fragment to display a color picker. The fragment uses the parent's color view model
|
||||
* to communicate with the caller.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ColorDialogFragment extends DialogFragment {
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
ColorViewModel model = new ViewModelProvider(getParentFragment()).get(ColorViewModel.class);
|
||||
DialogColorBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_color, container, false);
|
||||
binding.setModel(model);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
View view = inflater.inflate(R.layout.dialog_color, null);
|
||||
binding.colorSliderRed.setValue(model.getRed().getValue());
|
||||
binding.colorSliderGreen.setValue(model.getGreen().getValue());
|
||||
binding.colorSliderBlue.setValue(model.getBlue().getValue());
|
||||
binding.colorSliderRed.addOnChangeListener((slider, value, fromUser) -> {
|
||||
if (fromUser) model.getRed().setValue(value);
|
||||
});
|
||||
binding.colorSliderGreen.addOnChangeListener((slider, value, fromUser) -> {
|
||||
if (fromUser) model.getGreen().setValue(value);
|
||||
});
|
||||
binding.colorSliderBlue.addOnChangeListener((slider, value, fromUser) -> {
|
||||
if (fromUser) model.getBlue().setValue(value);
|
||||
});
|
||||
model.getColor().observe(getViewLifecycleOwner(), (color) -> {
|
||||
binding.colorResultText.setTextColor(color);
|
||||
binding.colorResultImage.setColorFilter(color);
|
||||
});
|
||||
binding.buttonOk.setOnClickListener((v) -> {
|
||||
model.setState(ColorViewModel.State.CONFIRMED);
|
||||
dismiss();
|
||||
});
|
||||
binding.buttonCancel.setOnClickListener((v) -> {
|
||||
model.setState(ColorViewModel.State.DISMISSED);
|
||||
dismiss();
|
||||
});
|
||||
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel(@NonNull DialogInterface dialog) {
|
||||
ColorViewModel model = new ViewModelProvider(getParentFragment()).get(ColorViewModel.class);
|
||||
model.setState(ColorViewModel.State.DISMISSED);
|
||||
super.onCancel(dialog);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.TypedValue;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewPropertyAnimator;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.view.animation.AnimationSet;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.core.widget.ImageViewCompat;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.Observer;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
import androidx.navigation.Navigation;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentConnectBinding;
|
||||
import com.mowesta.android.app.model.ConnectViewModel;
|
||||
import com.mowesta.android.app.util.DisplayUtils;
|
||||
import com.mowesta.android.feign.model.DeviceHandle;
|
||||
|
||||
/**
|
||||
* The fragment to connect a weather station which primarily shows a progress
|
||||
* animation while the process is running in the view model.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ConnectFragment extends Fragment {
|
||||
|
||||
/**
|
||||
* The arguments for this fragment, provided by the setup fragment
|
||||
* and forwarded to the view model.
|
||||
*/
|
||||
public static class Args {
|
||||
|
||||
/** The longitude. **/
|
||||
private double longitude;
|
||||
/** The latitude. **/
|
||||
private double latitude;
|
||||
/** The wifi ssid. **/
|
||||
private String network;
|
||||
/** The wifi password. **/
|
||||
private String password;
|
||||
/** The device name. **/
|
||||
private String device;
|
||||
|
||||
/**
|
||||
* Creates a new set of arguments.
|
||||
*
|
||||
* @param device The device.
|
||||
* @param network The network.
|
||||
* @param password The password.
|
||||
* @param longitude The longitude.
|
||||
* @param latitude The latitude.
|
||||
*/
|
||||
public Args(String device, String network, String password, double longitude, double latitude) {
|
||||
this.device = device;
|
||||
this.network = network;
|
||||
this.password = password;
|
||||
this.latitude = latitude;
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the latitude.
|
||||
*
|
||||
* @return The latitude.
|
||||
*/
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the longitude.
|
||||
*
|
||||
* @return The longitude.
|
||||
*/
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the device name.
|
||||
*
|
||||
* @return The device name.
|
||||
*/
|
||||
public String getDevice() {
|
||||
return device;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the network name.
|
||||
*
|
||||
* @return The network name.
|
||||
*/
|
||||
public String getNetwork() {
|
||||
return network;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the network password.
|
||||
*
|
||||
* @return The network password.
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a bundle from the arguments.
|
||||
*
|
||||
* @return A bundle from the arguments.
|
||||
*/
|
||||
public @NonNull Bundle asBundle() {
|
||||
Bundle result = new Bundle();
|
||||
result.putDouble("longitude", longitude);
|
||||
result.putDouble("latitude", latitude);
|
||||
result.putString("network", network);
|
||||
result.putString("password", password);
|
||||
result.putString("device", device);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the arguments from the bundle, if possible.
|
||||
*
|
||||
* @param bundle The bundle.
|
||||
* @return The args or null.
|
||||
*/
|
||||
public static @Nullable Args fromBundle(@Nullable Bundle bundle) {
|
||||
if (bundle == null) return null;
|
||||
double longitude = bundle.getDouble("longitude", -190);
|
||||
if (longitude < -180) return null;
|
||||
double latitude = bundle.getDouble("latitude", -100);
|
||||
if (latitude < -90) return null;
|
||||
String network = bundle.getString("network", null);
|
||||
if (network == null) return null;
|
||||
String password = bundle.getString("password", null);
|
||||
if (password == null) return null;
|
||||
String device = bundle.getString("device", null);
|
||||
if (device == null) return null;
|
||||
return new Args(device, network, password, longitude, latitude);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The current animation set.
|
||||
*/
|
||||
private AnimatorSet animation;
|
||||
|
||||
/**
|
||||
* The binding to access the views.
|
||||
*/
|
||||
private FragmentConnectBinding binding;
|
||||
|
||||
/**
|
||||
* The runnable to navigate to the device, when the setup
|
||||
* completes.
|
||||
*/
|
||||
private Runnable navigator;
|
||||
|
||||
/**
|
||||
* The handler to post events asynchronously.
|
||||
*/
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_connect, container, false);
|
||||
ConnectViewModel model = new ViewModelProvider(this).get(ConnectViewModel.class);
|
||||
binding.setModel(model);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setRetryListener(() -> {
|
||||
model.retry();
|
||||
});
|
||||
Observer<ConnectViewModel.State> animator = (state) -> {
|
||||
if (! model.getRetryVisible().getValue()) {
|
||||
startAnimation(state);
|
||||
}
|
||||
};
|
||||
model.getState().observe(getViewLifecycleOwner(), animator);
|
||||
model.getRetryVisible().observe(getViewLifecycleOwner(), (stopped) -> {
|
||||
if (stopped) {
|
||||
cancelAnimations();
|
||||
} else {
|
||||
startAnimation(model.getState().getValue());
|
||||
}
|
||||
});
|
||||
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
navigator = () -> {
|
||||
NavOptions.Builder opts = new NavOptions.Builder().setEnterAnim(R.anim.slide_in_right)
|
||||
.setExitAnim(R.anim.slide_out_left).setPopUpTo(R.id.destination_drawer, false);
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putLong("id", model.getDeviceHandle().getId());
|
||||
controller.navigate(R.id.destination_device, bundle, opts.build());
|
||||
};
|
||||
|
||||
model.getState().observe(getViewLifecycleOwner(), (state) -> {
|
||||
if (state == ConnectViewModel.State.COMPLETE) {
|
||||
handler.postDelayed(navigator, 5000);
|
||||
}
|
||||
});
|
||||
Args args = Args.fromBundle(getArguments());
|
||||
if (args == null) {
|
||||
getActivity().onBackPressed();
|
||||
} else {
|
||||
model.init(args);
|
||||
}
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
cancelAnimations();
|
||||
handler.removeCallbacks(navigator);
|
||||
super.onDestroyView();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts an animation that depends on the state.
|
||||
*
|
||||
* @param state The state.
|
||||
*/
|
||||
private void startAnimation(ConnectViewModel.State state) {
|
||||
cancelAnimations();
|
||||
if (state != null) {
|
||||
ImageView v = null;
|
||||
switch (state) {
|
||||
case DEVICE:
|
||||
v = binding.connectDevice;
|
||||
break;
|
||||
case NETWORK:
|
||||
v = binding.connectNetwork;
|
||||
break;
|
||||
case CONFIGURE:
|
||||
v = binding.connectConfigure;
|
||||
break;
|
||||
case COMPLETE:
|
||||
animation = new AnimatorSet();
|
||||
ObjectAnimator blend = ObjectAnimator.ofFloat(binding.connectSun, "alpha", 0f, 1f);
|
||||
blend.setInterpolator(new LinearInterpolator());
|
||||
blend.setDuration(5000);
|
||||
ObjectAnimator move = ObjectAnimator.ofFloat(binding.connectSun, "translationY", DisplayUtils.dpToPixels(getContext(), 48), 0f);
|
||||
move.setInterpolator(new LinearInterpolator());
|
||||
move.setDuration(5000);
|
||||
animation.playTogether(blend, move);
|
||||
animation.start();
|
||||
break;
|
||||
}
|
||||
if (v != null) {
|
||||
int color = ContextCompat.getColor(getActivity(), R.color.accent);
|
||||
ImageViewCompat.setImageTintList(v, ColorStateList.valueOf(color));
|
||||
ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 1f, 1.4f, 1f);
|
||||
ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1f, 1.4f, 1f);
|
||||
scaleX.setRepeatCount(ObjectAnimator.INFINITE);
|
||||
scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
scaleX.setDuration(750);
|
||||
scaleY.setRepeatCount(ObjectAnimator.INFINITE);
|
||||
scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
scaleY.setDuration(750);
|
||||
animation = new AnimatorSet();
|
||||
animation.playTogether(scaleX, scaleY);
|
||||
animation.start();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels all running animations and resets the view state.
|
||||
*/
|
||||
private void cancelAnimations() {
|
||||
if (animation != null) {
|
||||
animation.cancel();
|
||||
animation = null;
|
||||
}
|
||||
if (binding != null) {
|
||||
binding.connectSun.setAlpha(0f);
|
||||
TypedValue typedValue = new TypedValue();
|
||||
getActivity().getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
|
||||
int color = ContextCompat.getColor(getActivity(), typedValue.resourceId);
|
||||
ImageViewCompat.setImageTintList(binding.connectConfigure, ColorStateList.valueOf(color));
|
||||
ImageViewCompat.setImageTintList(binding.connectDevice, ColorStateList.valueOf(color));
|
||||
ImageViewCompat.setImageTintList(binding.connectNetwork, ColorStateList.valueOf(color));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
@@ -27,14 +26,11 @@ import com.locoslab.android.leafless.polyline.Polyline;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.databinding.FragmentCountryBinding;
|
||||
import com.mowesta.android.app.databinding.FragmentStateBinding;
|
||||
import com.mowesta.android.app.model.AbstractPlaceViewModel;
|
||||
import com.mowesta.android.app.model.BindingTransforms;
|
||||
import com.mowesta.android.app.binding.BindingTransforms;
|
||||
import com.mowesta.android.app.model.CountryViewModel;
|
||||
import com.mowesta.android.app.model.StateViewModel;
|
||||
import com.mowesta.android.app.util.MapViewUtil;
|
||||
import com.mowesta.android.feign.model.Country;
|
||||
import com.mowesta.android.feign.model.State;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -109,7 +105,7 @@ public class CountryFragment extends AbstractPlaceFragment {
|
||||
model.getCities().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
MapViewUtil.removePolylines(mapView, polylines);
|
||||
polylines.clear();
|
||||
|
||||
+51
@@ -4,6 +4,8 @@ import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -11,10 +13,14 @@ import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.DialogCustomizeBinding;
|
||||
import com.mowesta.android.app.model.CustomizeViewModel;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A bottom sheet dialog that enables the user to customize the weather data.
|
||||
*
|
||||
@@ -30,7 +36,52 @@ public class CustomizeDialogFragment extends BottomSheetDialogFragment {
|
||||
binding.setModel(model);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setCloseListener(() -> { this.dismiss(); });
|
||||
List<String> systems = getSystemEntries();
|
||||
binding.customizeSystem.setAdapter(createAdapter(systems));
|
||||
List<String> temperatures = getTemperatureEntries();
|
||||
binding.customizeTemperature.setAdapter(createAdapter(temperatures));
|
||||
model.getUnitSystem().observe(getViewLifecycleOwner(), (value) -> {
|
||||
if (value != null) {
|
||||
binding.customizeSystem.setText(systems.get(value.ordinal()), false);
|
||||
}
|
||||
});
|
||||
model.getTemperatureUnit().observe(getViewLifecycleOwner(), (value) -> {
|
||||
if (value != null) {
|
||||
binding.customizeTemperature.setText(temperatures.get(value.ordinal()), false);
|
||||
}
|
||||
});
|
||||
binding.customizeSystem.setOnItemClickListener((parent, view, position, id) -> {
|
||||
if (position >= 0 && position < MowestaSettings.UnitSystem.values().length) {
|
||||
model.getUnitSystem().setValue(MowestaSettings.UnitSystem.values()[position]);
|
||||
}
|
||||
});
|
||||
binding.customizeTemperature.setOnItemClickListener((parent, view, position, id) -> {
|
||||
if (position >= 0 && position < MowestaSettings.TemperatureUnit.values().length) {
|
||||
model.getTemperatureUnit().setValue(MowestaSettings.TemperatureUnit.values()[position]);
|
||||
}
|
||||
});
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
private ArrayAdapter<String> createAdapter(List<String> strings) {
|
||||
return new ArrayAdapter<>(getContext(), R.layout.view_customize_entry, strings);
|
||||
}
|
||||
|
||||
private List<String> getSystemEntries() {
|
||||
List<String> result = new ArrayList<>(3);
|
||||
result.add(getString(R.string.customize_system_both));
|
||||
result.add(getString(R.string.customize_system_standard));
|
||||
result.add(getString(R.string.customize_system_imperial));
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<String> getTemperatureEntries() {
|
||||
List<String> result = new ArrayList<>(3);
|
||||
result.add(getString(R.string.customize_temperature_both));
|
||||
result.add(getString(R.string.customize_temperature_celsius));
|
||||
result.add(getString(R.string.customize_temperature_fahrenheit));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -102,8 +102,7 @@ public class DeviceFragment extends AbstractDiagramFragment {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUnitChanged() {
|
||||
super.onUnitChanged();
|
||||
public void onRefreshDiagram() {
|
||||
RecyclerView recyclerView = getView().findViewById(R.id.recycler);
|
||||
recyclerView.getAdapter().notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@@ -10,21 +10,20 @@ import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
import androidx.navigation.Navigation;
|
||||
import androidx.paging.PagedListAdapter;
|
||||
import androidx.recyclerview.widget.DiffUtil;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.DeviceEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.databinding.FragmentDevicesBinding;
|
||||
import com.mowesta.android.app.databinding.ViewDeviceEntryBinding;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.DevicesViewModel;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
@@ -41,16 +40,32 @@ public class DevicesFragment extends AbstractNetworkFragment {
|
||||
return new ViewModelProvider(this).get(DevicesViewModel.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentDevicesBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_devices, container, false);
|
||||
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
binding.setAddButtonListener(() -> {
|
||||
NavOptions.Builder opts = new NavOptions.Builder().setEnterAnim(R.anim.slide_in_right).setExitAnim(R.anim.slide_out_left);
|
||||
Bundle bundle = new Bundle();
|
||||
controller.navigate(R.id.destination_setup, bundle, opts.build());
|
||||
});
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
inflater.inflate(R.menu.menu_refresh, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem item) {
|
||||
if (item.getItemId() == R.id.action_refresh) {
|
||||
DevicesViewModel model = new ViewModelProvider(DevicesFragment.this).get(DevicesViewModel.class);
|
||||
model.reload();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
@@ -80,120 +95,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
|
||||
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_refresh, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
if (item.getItemId() == R.id.action_refresh) {
|
||||
DevicesViewModel model = new ViewModelProvider(this).get(DevicesViewModel.class);
|
||||
model.reload();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The view holder for the list of devices
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private static class DeviceEntryViewHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
/**
|
||||
* The binding with the device view.
|
||||
*/
|
||||
private ViewDeviceEntryBinding binding;
|
||||
|
||||
/**
|
||||
* Creates a new view holder for the binding.
|
||||
*
|
||||
* @param binding The binding.
|
||||
*/
|
||||
public DeviceEntryViewHolder(@NonNull ViewDeviceEntryBinding binding) {
|
||||
super(binding.getRoot());
|
||||
this.binding = binding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the model.
|
||||
*
|
||||
* @param device The device.
|
||||
*/
|
||||
public void setModel(Device device) {
|
||||
this.binding.setModel(device);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A callback to determine whether two devices are the same.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private static class DeviceCallback extends DiffUtil.ItemCallback<Device> {
|
||||
|
||||
@Override
|
||||
public boolean areItemsTheSame(@NonNull Device oldItem, @NonNull Device newItem) {
|
||||
return oldItem.getId() != null && oldItem.getId().equals(newItem.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean areContentsTheSame(@NonNull Device oldItem, @NonNull Device newItem) {
|
||||
return oldItem.getId() != null && oldItem.getId().equals(newItem.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A list adapter to display the list of devices.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private static class DeviceEntryPagedListAdapter extends PagedListAdapter<Device, DeviceEntryViewHolder> {
|
||||
|
||||
/**
|
||||
* The lifecycle owner.
|
||||
*/
|
||||
private @NonNull
|
||||
LifecycleOwner owner;
|
||||
|
||||
/**
|
||||
* The click listener.
|
||||
*/
|
||||
private @NonNull
|
||||
DevicesViewModel.OnDeviceSelectedListener listener;
|
||||
|
||||
/**
|
||||
* Creates a new paged list adapter that will inform
|
||||
* the listener about click events.
|
||||
*
|
||||
* @param owner The lifecycle owner.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public DeviceEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull DevicesViewModel.OnDeviceSelectedListener listener) {
|
||||
super(new DeviceCallback());
|
||||
this.owner = owner;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public DeviceEntryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
ViewDeviceEntryBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.view_device_entry, parent, false);
|
||||
DeviceEntryViewHolder holder = new DeviceEntryViewHolder(binding);
|
||||
binding.setListener(listener);
|
||||
binding.setLifecycleOwner(owner);
|
||||
return holder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull DeviceEntryViewHolder holder, int position) {
|
||||
holder.setModel(getItem(position));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import android.database.AbstractCursor;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuInflater;
|
||||
@@ -26,6 +28,7 @@ import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.SearchView;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.cursoradapter.widget.CursorAdapter;
|
||||
import androidx.customview.widget.Openable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
@@ -76,19 +79,13 @@ public class DrawerFragment extends AbstractNetworkFragment {
|
||||
return new ViewModelProvider(this).get(DrawerViewModel.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
// navigate to settings, if user pressed notification
|
||||
handleNotificationIntent();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the intent was generated by the background service and
|
||||
* opens the settings screen, if this is the case
|
||||
@@ -98,8 +95,8 @@ public class DrawerFragment extends AbstractNetworkFragment {
|
||||
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
|
||||
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
|
||||
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
|
||||
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
|
||||
getActivity().setIntent(new Intent());
|
||||
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,49 +108,52 @@ public class DrawerFragment extends AbstractNetworkFragment {
|
||||
Toolbar toolbar = view.findViewById(R.id.toolbar);
|
||||
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
|
||||
loadingProgressBar = view.findViewById(R.id.progress_bar);
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
|
||||
menuInflater.inflate(R.menu.menu_search, menu);
|
||||
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
|
||||
search.setQueryHint(getString(R.string.action_search));
|
||||
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
|
||||
complete.setDropDownBackgroundResource(R.color.bg_search);
|
||||
final DrawerViewModel model = new ViewModelProvider(DrawerFragment.this).get(DrawerViewModel.class);
|
||||
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
|
||||
@Override
|
||||
public boolean onQueryTextSubmit(String query) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onQueryTextChange(String newText) {
|
||||
model.setTerm(newText);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
|
||||
@Override
|
||||
public boolean onSuggestionSelect(int position) {
|
||||
showLocation(model, position);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSuggestionClick(int position) {
|
||||
showLocation(model, position);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
|
||||
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
|
||||
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
|
||||
}
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
return view;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_search, menu);
|
||||
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
|
||||
search.setQueryHint(getString(R.string.action_search));
|
||||
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
|
||||
complete.setDropDownBackgroundResource(R.color.bg_search);
|
||||
final DrawerViewModel model = new ViewModelProvider(this).get(DrawerViewModel.class);
|
||||
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
|
||||
@Override
|
||||
public boolean onQueryTextSubmit(String query) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onQueryTextChange(String newText) {
|
||||
model.setTerm(newText);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
|
||||
@Override
|
||||
public boolean onSuggestionSelect(int position) {
|
||||
showLocation(model, position);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSuggestionClick(int position) {
|
||||
showLocation(model, position);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
|
||||
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
|
||||
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
|
||||
}
|
||||
|
||||
private void showLocation(DrawerViewModel model, int position) {
|
||||
LocationHierarchyPage page = model.getResults().getValue();
|
||||
LocationHierarchy dest = page.getElements().get(position);
|
||||
|
||||
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.view.MenuProvider;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
@@ -17,16 +18,20 @@ import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
import androidx.navigation.Navigation;
|
||||
import androidx.recyclerview.widget.ItemTouchHelper;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.databinding.ViewFavoriteEntryBinding;
|
||||
import com.mowesta.android.app.model.CustomizeViewModel;
|
||||
import com.mowesta.android.app.model.FavoritesViewModel;
|
||||
import com.mowesta.android.app.model.FavoritesViewModel.OnFavoriteSelectedListener;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.util.TabletUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -36,23 +41,53 @@ import java.util.List;
|
||||
*/
|
||||
public class FavoritesFragment extends Fragment {
|
||||
|
||||
private static final String TAG_ADVERTISEMENT = "ad";
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
// possibly show the ad for eiszeit
|
||||
AdvertiseDialogFragment adf = new AdvertiseDialogFragment();
|
||||
if (adf.shouldShow(getContext()) && getChildFragmentManager().findFragmentByTag(TAG_ADVERTISEMENT) == null) {
|
||||
adf.show(getChildFragmentManager(), TAG_ADVERTISEMENT);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
return inflater.inflate(R.layout.fragment_favorites, container, false);
|
||||
View view = inflater.inflate(R.layout.fragment_favorites, container, false);
|
||||
getActivity().addMenuProvider(new MenuProvider() {
|
||||
@Override
|
||||
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
inflater.inflate(R.menu.menu_unit, menu);
|
||||
inflater.inflate(R.menu.menu_refresh, menu);
|
||||
// remove this item, since it would not have an effect here
|
||||
MenuItem item = menu.findItem(R.id.action_unit_system);
|
||||
if (item != null) item.setVisible(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemSelected(@NonNull MenuItem item) {
|
||||
if (item.getItemId() == R.id.action_refresh) {
|
||||
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
|
||||
model.refresh();
|
||||
return true;
|
||||
} else if (item.getItemId() == R.id.action_temperature_unit) {
|
||||
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
|
||||
unit.show(getChildFragmentManager(), "unit");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, getViewLifecycleOwner());
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
RecyclerView recyclerView = view.findViewById(R.id.recycler);
|
||||
TabletUtil.setGridLayout(recyclerView, 300);
|
||||
TabletUtil.setGridLayout(recyclerView, 350);
|
||||
SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
|
||||
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
|
||||
model.getRefreshing().observe(getViewLifecycleOwner(), (refreshing) -> {
|
||||
@@ -78,6 +113,55 @@ public class FavoritesFragment extends Fragment {
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
ItemTouchHelper touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
|
||||
private int selection;
|
||||
private int target;
|
||||
private List<Favorite> favorites;
|
||||
|
||||
@Override
|
||||
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
|
||||
return makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
|
||||
int fromPosition = viewHolder.getBindingAdapterPosition();
|
||||
int toPosition = target.getBindingAdapterPosition();
|
||||
this.target = toPosition;
|
||||
recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
|
||||
super.onSelectedChanged(viewHolder, actionState);
|
||||
swipeRefreshLayout.setEnabled(actionState == ItemTouchHelper.ACTION_STATE_IDLE);
|
||||
if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
|
||||
List<Favorite> current = model.getFavorites().getValue();
|
||||
if (selection != -1 && target != -1 && current == favorites) {
|
||||
favorites.add(target, favorites.remove(selection));
|
||||
model.updateFavorites(favorites);
|
||||
}
|
||||
selection = -1;
|
||||
target = -1;
|
||||
favorites = null;
|
||||
} else if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
|
||||
favorites = model.getFavorites().getValue();
|
||||
selection = viewHolder.getBindingAdapterPosition();
|
||||
target = -1;
|
||||
}
|
||||
}
|
||||
});
|
||||
touchHelper.attachToRecyclerView(recyclerView);
|
||||
CustomizeViewModel customize = new ViewModelProvider(getActivity()).get(CustomizeViewModel.class);
|
||||
customize.getUnitSystem().observe(getViewLifecycleOwner(), (v) -> recyclerView.getAdapter().notifyDataSetChanged());
|
||||
customize.getTemperatureUnit().observe(getViewLifecycleOwner(), (v) -> recyclerView.getAdapter().notifyDataSetChanged());
|
||||
View layoutHelp = view.findViewById(R.id.favorites_help);
|
||||
View layoutList = view.findViewById(R.id.favorites_list);
|
||||
model.getFavorites().observe(getViewLifecycleOwner(), (list)-> {
|
||||
@@ -87,22 +171,6 @@ public class FavoritesFragment extends Fragment {
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
|
||||
super.onCreateOptionsMenu(menu, inflater);
|
||||
inflater.inflate(R.menu.menu_refresh, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
if (item.getItemId() == R.id.action_refresh) {
|
||||
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
|
||||
model.refresh();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The view holder for favorites.
|
||||
*
|
||||
@@ -115,6 +183,7 @@ public class FavoritesFragment extends Fragment {
|
||||
*/
|
||||
private @NonNull ViewFavoriteEntryBinding binding;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new view holder.
|
||||
*
|
||||
@@ -133,6 +202,16 @@ public class FavoritesFragment extends Fragment {
|
||||
*/
|
||||
public void setModel(Favorite favorite) {
|
||||
this.binding.setModel(favorite);
|
||||
binding.getRoot().setVisibility(favorite == null || favorite.getCity() == null ? View.GONE : View.VISIBLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the favorite which may be null.
|
||||
*
|
||||
* @return The favorite.
|
||||
*/
|
||||
public Favorite getModel() {
|
||||
return binding.getModel();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -195,6 +274,7 @@ public class FavoritesFragment extends Fragment {
|
||||
public int getItemCount() {
|
||||
return (liveData.getValue() == null)?0: liveData.getValue().size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.CityEntryListAdapter;
|
||||
import com.mowesta.android.app.database.Widget;
|
||||
import com.mowesta.android.app.database.WidgetDatabase;
|
||||
import com.mowesta.android.app.databinding.FragmentForecastWidgetBinding;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.ColorViewModel;
|
||||
import com.mowesta.android.app.model.ForecastWidgetViewModel;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.widget.ForecastWidgetProvider;
|
||||
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
|
||||
/**
|
||||
* A fragment to configure the forecast widget.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ForecastWidgetFragment extends AbstractNetworkFragment {
|
||||
|
||||
/**
|
||||
* The bundle extra to store the widget id.
|
||||
*/
|
||||
private static final String EXTRA_WIDGET_ID = "widget_id";
|
||||
|
||||
@Override
|
||||
protected AbstractNetworkViewModel getNetworkViewModel() {
|
||||
return new ViewModelProvider(this).get(ForecastWidgetViewModel.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the widget id that is currently configured.
|
||||
*
|
||||
* @return The widget id that is currently configured.
|
||||
*/
|
||||
public int getWidgetId() {
|
||||
return getArguments().getInt(EXTRA_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance with the widget id.
|
||||
*
|
||||
* @param widgetId The widget id.
|
||||
* @return The instance.
|
||||
*/
|
||||
public static ForecastWidgetFragment newInstance(int widgetId) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt(EXTRA_WIDGET_ID, widgetId);
|
||||
ForecastWidgetFragment fragment = new ForecastWidgetFragment();
|
||||
fragment.setArguments(b);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
protected View getErrorAnchorView() {
|
||||
return getView().findViewById(R.id.layout_coordinator);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentForecastWidgetBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_forecast_widget, container, false);
|
||||
ForecastWidgetViewModel model = new ViewModelProvider(this).get(ForecastWidgetViewModel.class);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setModel(model);
|
||||
model.getColor().observe(getViewLifecycleOwner(), (color) -> {
|
||||
binding.buttonColor.setColorFilter(color);
|
||||
});
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
ForecastWidgetViewModel model = new ViewModelProvider(this).get(ForecastWidgetViewModel.class);
|
||||
ColorViewModel color = new ViewModelProvider(this).get(ColorViewModel.class);
|
||||
color.getState().observe(getViewLifecycleOwner(), state -> {
|
||||
if (state == ColorViewModel.State.CONFIRMED) {
|
||||
model.getColor().setValue(color.getColor().getValue());
|
||||
}
|
||||
});
|
||||
RecyclerView recyclerView = view.findViewById(R.id.recycler);
|
||||
recyclerView.setAdapter(new CityEntryListAdapter(
|
||||
getViewLifecycleOwner(),
|
||||
(selection)-> model.getSelection().setValue(selection),
|
||||
model.getCities(),
|
||||
model.getSelection()));
|
||||
model.getFinished().observe(getViewLifecycleOwner(), (c) -> {
|
||||
if (c != null) finish(c, model.getCelsius().getValue(), model.getColor().getValue());
|
||||
});
|
||||
model.getDialog().observe(getViewLifecycleOwner(), (d) -> {
|
||||
if (d) {
|
||||
color.setColor(model.getColor().getValue());
|
||||
color.setState(ColorViewModel.State.VISIBLE);
|
||||
ColorDialogFragment cdf = new ColorDialogFragment();
|
||||
cdf.show(getChildFragmentManager(), "color");
|
||||
model.getDialog().setValue(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes the the configuration and stores the widget configuration in the database.
|
||||
*
|
||||
* @param city The city.
|
||||
* @param color The color.
|
||||
* @param celsius A flag to indicate whether the widget uses celsius or fahrenheit.
|
||||
*/
|
||||
public void finish(City city, boolean celsius, int color) {
|
||||
Activity activity = getActivity();
|
||||
Context app = activity.getApplicationContext();
|
||||
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<>((input, database)-> {
|
||||
long now = System.currentTimeMillis();
|
||||
Widget w = new Widget();
|
||||
w.setReference(input);
|
||||
w.setType(Widget.TYPE_FORECAST);
|
||||
w.setCelsius(celsius);
|
||||
w.setDataId(city.getId());
|
||||
w.setData(city);
|
||||
w.setDataTime(now);
|
||||
w.setColor(color);
|
||||
database.getAccessor().add(w);
|
||||
return w;
|
||||
}, (input, result) -> {
|
||||
ForecastWidgetProvider provider = new ForecastWidgetProvider();
|
||||
provider.triggerUpdate(app, input, true);
|
||||
if (!activity.isDestroyed()) {
|
||||
activity.finish();
|
||||
}
|
||||
});
|
||||
|
||||
PeriodicWidgetWorker.scheduleUpdates(app);
|
||||
int id = getWidgetId();
|
||||
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
|
||||
Intent resultValue = new Intent();
|
||||
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
|
||||
activity.setResult(Activity.RESULT_OK, resultValue);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -52,7 +52,16 @@ public class LoginFragment extends Fragment {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_devices, null, b.build());
|
||||
break;
|
||||
case COLLECTION:
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
try {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// this is most likely bug in the navigation library, since it cannot find the
|
||||
// node in the xml file which is technically impossible (probably a race during loading)
|
||||
NavOptions.Builder builder = new NavOptions.Builder().setPopUpTo(R.id.destination_login, true);
|
||||
builder.setEnterAnim(R.anim.slide_in_right);
|
||||
builder.setExitAnim(R.anim.slide_out_left);
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_collection, null, builder.build());
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Application;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavDeepLinkBuilder;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.MowestaActivity;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.DeviceEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.database.Widget;
|
||||
import com.mowesta.android.app.database.WidgetDatabase;
|
||||
import com.mowesta.android.app.databinding.FragmentMeasureWidgetBinding;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.ColorViewModel;
|
||||
import com.mowesta.android.app.model.MeasureWidgetViewModel;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.widget.MeasureWidgetProvider;
|
||||
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A fragment to configure the measure widget.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasureWidgetFragment extends AbstractNetworkFragment {
|
||||
|
||||
/**
|
||||
* The bundle extra to store the widget id.
|
||||
*/
|
||||
private static final String EXTRA_WIDGET_ID = "widget_id";
|
||||
|
||||
@Override
|
||||
protected AbstractNetworkViewModel getNetworkViewModel() {
|
||||
return new ViewModelProvider(this).get(MeasureWidgetViewModel.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the widget id that is currently configured.
|
||||
*
|
||||
* @return The widget id that is currently configured.
|
||||
*/
|
||||
public int getWidgetId() {
|
||||
return getArguments().getInt(EXTRA_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance with the widget id.
|
||||
*
|
||||
* @param widgetId The widget id.
|
||||
* @return The instance.
|
||||
*/
|
||||
public static MeasureWidgetFragment newInstance(int widgetId) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt(EXTRA_WIDGET_ID, widgetId);
|
||||
MeasureWidgetFragment fragment = new MeasureWidgetFragment();
|
||||
fragment.setArguments(b);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
protected View getErrorAnchorView() {
|
||||
return getView().findViewById(R.id.layout_coordinator);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentMeasureWidgetBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_measure_widget, container, false);
|
||||
MeasureWidgetViewModel model = new ViewModelProvider(this).get(MeasureWidgetViewModel.class);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setModel(model);
|
||||
List<String> systems = getSystemEntries();
|
||||
binding.customizeSystem.setAdapter(createAdapter(systems));
|
||||
List<String> temperatures = getTemperatureEntries();
|
||||
binding.customizeTemperature.setAdapter(createAdapter(temperatures));
|
||||
model.getSi().observe(getViewLifecycleOwner(), (value) -> {
|
||||
binding.customizeSystem.setText(systems.get(value?0:1), false);
|
||||
});
|
||||
model.getCelsius().observe(getViewLifecycleOwner(), (value) -> {
|
||||
binding.customizeTemperature.setText(temperatures.get(value?0:1), false);
|
||||
});
|
||||
binding.customizeSystem.setOnItemClickListener((parent, view, position, id) -> {
|
||||
model.getSi().setValue(position == 0);
|
||||
});
|
||||
binding.customizeTemperature.setOnItemClickListener((parent, view, position, id) -> {
|
||||
model.getCelsius().setValue(position == 0);
|
||||
});
|
||||
model.getColor().observe(getViewLifecycleOwner(), (color) -> {
|
||||
binding.buttonColor.setColorFilter(color);
|
||||
});
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
MeasureWidgetViewModel model = new ViewModelProvider(this).get(MeasureWidgetViewModel.class);
|
||||
ColorViewModel color = new ViewModelProvider(this).get(ColorViewModel.class);
|
||||
color.getState().observe(getViewLifecycleOwner(), state -> {
|
||||
if (state == ColorViewModel.State.CONFIRMED) {
|
||||
model.getColor().setValue(color.getColor().getValue());
|
||||
}
|
||||
});
|
||||
RecyclerView recyclerView = view.findViewById(R.id.recycler);
|
||||
DeviceEntryPagedListAdapter adapter = new DeviceEntryPagedListAdapter(getViewLifecycleOwner(), (device) -> {
|
||||
model.getSelection().setValue(device);
|
||||
}, model.getSelection());
|
||||
IApp app = (IApp)getContext().getApplicationContext();
|
||||
app.getUserRepository().getCredentials().observe(getViewLifecycleOwner(), (c) -> model.setUserCredentials(c));
|
||||
SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
|
||||
model.getDevices().observe(getViewLifecycleOwner(), (list) -> {
|
||||
adapter.submitList(list);
|
||||
swipeRefreshLayout.setRefreshing(false);
|
||||
});
|
||||
recyclerView.setAdapter(adapter);
|
||||
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
|
||||
model.getFinished().observe(getViewLifecycleOwner(), (c) -> {
|
||||
if (c != null) finish(c, model.getCelsius().getValue(), model.getSi().getValue(), model.getColor().getValue());
|
||||
});
|
||||
model.getLogin().observe(getViewLifecycleOwner(), (v) -> {
|
||||
if (v) {
|
||||
startActivity(new Intent(getContext(), MowestaActivity.class));
|
||||
getActivity().finish();
|
||||
}
|
||||
});
|
||||
model.getDialog().observe(getViewLifecycleOwner(), (d) -> {
|
||||
if (d) {
|
||||
color.setColor(model.getColor().getValue());
|
||||
color.setState(ColorViewModel.State.VISIBLE);
|
||||
ColorDialogFragment cdf = new ColorDialogFragment();
|
||||
cdf.show(getChildFragmentManager(), "color");
|
||||
model.getDialog().setValue(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array adapter using the customize view entry.
|
||||
*
|
||||
* @param strings The strings.
|
||||
* @return The array adapter.
|
||||
*/
|
||||
private ArrayAdapter<String> createAdapter(List<String> strings) {
|
||||
return new ArrayAdapter<>(getContext(), R.layout.view_customize_entry, strings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the strings in the system combobox.
|
||||
*
|
||||
* @return The strings.
|
||||
*/
|
||||
private List<String> getSystemEntries() {
|
||||
List<String> result = new ArrayList<>(3);
|
||||
result.add(getString(R.string.customize_system_standard));
|
||||
result.add(getString(R.string.customize_system_imperial));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the strings in the temperature combobx.
|
||||
*
|
||||
* @return The strings.
|
||||
*/
|
||||
private List<String> getTemperatureEntries() {
|
||||
List<String> result = new ArrayList<>(3);
|
||||
result.add(getString(R.string.customize_temperature_celsius));
|
||||
result.add(getString(R.string.customize_temperature_fahrenheit));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes the the configuration and stores the widget configuration in the database.
|
||||
*
|
||||
* @param device The device.
|
||||
* @param celsius A flag to indicate whether the widget uses celsius or fahrenheit.
|
||||
* @param color The widget color.
|
||||
* @param si A flag to indicate which measurement unit system.
|
||||
*/
|
||||
public void finish(Device device, boolean celsius, boolean si, int color) {
|
||||
Activity activity = getActivity();
|
||||
Context app = activity.getApplicationContext();
|
||||
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<>((input, database)-> {
|
||||
long now = System.currentTimeMillis();
|
||||
Widget w = new Widget();
|
||||
w.setReference(input);
|
||||
w.setType(Widget.TYPE_MEASURE);
|
||||
w.setCelsius(celsius);
|
||||
w.setColor(color);
|
||||
w.setSi(si);
|
||||
w.setDataId(device.getId());
|
||||
w.setData(device);
|
||||
w.setDataTime(now);
|
||||
database.getAccessor().add(w);
|
||||
return w;
|
||||
}, (input, result) -> {
|
||||
MeasureWidgetProvider provider = new MeasureWidgetProvider();
|
||||
provider.triggerUpdate(app, input, true);
|
||||
if (!activity.isDestroyed()) {
|
||||
activity.finish();
|
||||
}
|
||||
});
|
||||
PeriodicWidgetWorker.scheduleUpdates(app);
|
||||
int id = getWidgetId();
|
||||
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
|
||||
Intent resultValue = new Intent();
|
||||
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
|
||||
activity.setResult(Activity.RESULT_OK, resultValue);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import android.content.Intent;
|
||||
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Settings;
|
||||
@@ -152,7 +153,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
|
||||
View v = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
|
||||
settings = new MowestaSettings(getActivity().getApplication());
|
||||
this.settings = ((IApp)getContext().getApplicationContext()).getSettings();
|
||||
updateBuild();
|
||||
updateNotification();
|
||||
bindDevice();
|
||||
@@ -200,8 +201,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
*/
|
||||
private void updateBuild() {
|
||||
try {
|
||||
ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(getActivity().getPackageName(), 0);
|
||||
PackageInfo pi = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
|
||||
String summary = getResources().getString(R.string.setting_about_build_summary);
|
||||
summary = summary.replace("$version$", BuildConfig.VERSION_NAME);
|
||||
summary = summary.replace("$code$", "" + BuildConfig.VERSION_CODE);
|
||||
@@ -334,7 +333,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
setClickListener(KEY_ABOUT_TERMS, new Preference.OnPreferenceClickListener() {
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
Navigation.findNavController(getActivity(), R.id.navigation_app).navigate(R.id.destination_terms);
|
||||
Navigation.findNavController(getActivity(), R.id.navigation_app).navigate(R.id.destination_review);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
@@ -432,7 +431,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
b.setTitle(R.string.setting_privacy_reset_title);
|
||||
b.setMessage(R.string.setting_privacy_reset_message);
|
||||
b.setIcon(R.drawable.ic_delete_forever_normal_24);
|
||||
b.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
|
||||
b.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
// stop the service and its background processing
|
||||
@@ -442,7 +441,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
// reset the settings
|
||||
MowestaApp app = (MowestaApp)activity.getApplication();
|
||||
SdkRepository sdk = SdkRepository.getInstance(app);
|
||||
MowestaSettings settings = new MowestaSettings(app);
|
||||
MowestaSettings settings = app.getSettings();
|
||||
settings.setPrivacyMeasure(false);
|
||||
settings.setCollectionShown(false);
|
||||
app.getUserRepository().clearCredentials();
|
||||
@@ -460,7 +459,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
|
||||
}).execute();
|
||||
}
|
||||
});
|
||||
b.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
|
||||
b.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
// nothing to be done
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Settings;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewPropertyAnimator;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
import android.view.animation.OvershootInterpolator;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
import androidx.navigation.Navigation;
|
||||
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.MowestaActivity;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentSetupBinding;
|
||||
import com.mowesta.android.app.model.SetupViewModel;
|
||||
import com.mowesta.android.app.util.DisplayUtils;
|
||||
import com.mowesta.android.app.util.PermissionUtil;
|
||||
|
||||
/**
|
||||
* The setup fragment that is used to add a weather station to
|
||||
* the account.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class SetupFragment extends Fragment {
|
||||
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentSetupBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_setup, container, false);
|
||||
SetupViewModel model = new ViewModelProvider(this).get(SetupViewModel.class);
|
||||
model.getManualPosition().observe(getViewLifecycleOwner(), (manualPosition) -> {
|
||||
if (! manualPosition) {
|
||||
binding.setupNetworkName.requestFocus();
|
||||
}
|
||||
});
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setModel(model);
|
||||
binding.setInfoButtonListener(() -> {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse(getString(R.string.setup_url)));
|
||||
try {
|
||||
startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Snackbar.make(container, R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
binding.setGpsButtonListener(() -> {
|
||||
SetupViewModel.GpsStatus status = model.registerGpsReceiver();
|
||||
switch (status) {
|
||||
case PROHIBITED:
|
||||
ActivityCompat.requestPermissions(getActivity(), PermissionUtil.getForegroundPermissions(getActivity()), MowestaActivity.CODE_REQUEST_FOREGROUND_PERMISSIONS);
|
||||
break;
|
||||
case DISABLED:
|
||||
Snackbar.make(container, R.string.setup_error_gps_disabled, Snackbar.LENGTH_LONG).setAction(R.string.button_configure, (v) -> {
|
||||
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
|
||||
try {
|
||||
startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
// should never happen
|
||||
}
|
||||
}).show();
|
||||
break;
|
||||
default:
|
||||
// success
|
||||
break;
|
||||
}
|
||||
});
|
||||
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
binding.setReadyButtonListener(() -> {
|
||||
model.unregisterGpsReciever();
|
||||
ConnectFragment.Args args = model.getArgs();
|
||||
if (args != null) {
|
||||
NavOptions.Builder opts = new NavOptions.Builder().setEnterAnim(R.anim.slide_in_right).setExitAnim(R.anim.slide_out_left);
|
||||
controller.navigate(R.id.destination_connect, args.asBundle(), opts.build());
|
||||
}
|
||||
});
|
||||
if (model.isAnimate()) {
|
||||
model.setAnimate(false); // only animate on first entry
|
||||
binding.setupLayout.setAlpha(0);
|
||||
AnimatorSet set = new AnimatorSet();
|
||||
ObjectAnimator rotate = ObjectAnimator.ofFloat(binding.setupIcon, "rotation", 360*10f, 0f);
|
||||
rotate.setDuration(2000);
|
||||
rotate.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
ObjectAnimator scaleX = ObjectAnimator.ofFloat(binding.setupIcon, "scaleX", 10, 1f);
|
||||
scaleX.setInterpolator(new LinearInterpolator());
|
||||
scaleX.setDuration(750);
|
||||
ObjectAnimator scaleY = ObjectAnimator.ofFloat(binding.setupIcon, "scaleY", 10, 1f);
|
||||
scaleY.setInterpolator(new LinearInterpolator());
|
||||
scaleY.setDuration(750);
|
||||
float offset = DisplayUtils.dpToPixels(getContext(), 48 * 5);
|
||||
ObjectAnimator moveX = ObjectAnimator.ofFloat(binding.setupIcon, "translationY", offset, 0f);
|
||||
moveX.setInterpolator(new LinearInterpolator());
|
||||
moveX.setDuration(750);
|
||||
ObjectAnimator moveY = ObjectAnimator.ofFloat(binding.setupIcon, "translationX", -offset, 0f);
|
||||
moveY.setInterpolator(new LinearInterpolator());
|
||||
moveY.setDuration(750);
|
||||
ObjectAnimator blend = ObjectAnimator.ofFloat(binding.setupLayout, "alpha", 0f, 1f);
|
||||
blend.setInterpolator(new LinearInterpolator());
|
||||
blend.setDuration(1000);
|
||||
AnimatorSet m = new AnimatorSet();
|
||||
m.playTogether(scaleX, scaleY, moveX, moveY);
|
||||
|
||||
set.playSequentially(m, blend);
|
||||
AnimatorSet second = new AnimatorSet();
|
||||
second.playTogether(set, rotate);
|
||||
second.start();
|
||||
}
|
||||
return binding.getRoot();
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import androidx.fragment.app.Fragment;
|
||||
import androidx.navigation.Navigation;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -54,7 +55,7 @@ public class SplashFragment extends Fragment {
|
||||
/**
|
||||
* The handler.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The settings to check states.
|
||||
@@ -64,7 +65,7 @@ public class SplashFragment extends Fragment {
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
settings = new MowestaSettings(getActivity().getApplication());
|
||||
this.settings = ((IApp)getContext().getApplicationContext()).getSettings();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -78,6 +79,7 @@ public class SplashFragment extends Fragment {
|
||||
View title = root.findViewById(R.id.splash_title);
|
||||
View subtitle = root.findViewById(R.id.splash_subtitle);
|
||||
View world = root.findViewById(R.id.splash_world);
|
||||
View logos = root.findViewById(R.id.logo_panel);
|
||||
AnimatorSet set = new AnimatorSet();
|
||||
ValueAnimator gradientAnimator = ValueAnimator.ofFloat(0, 1);
|
||||
gradientAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
@@ -93,6 +95,10 @@ public class SplashFragment extends Fragment {
|
||||
ObjectAnimator worldAnimator = ObjectAnimator.ofFloat(world, "alpha", 0, 1);
|
||||
worldAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
worldAnimator.setDuration(750);
|
||||
logos.setAlpha(0);
|
||||
ObjectAnimator logoAnimator = ObjectAnimator.ofFloat(logos, "alpha", 0, 1);
|
||||
logoAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
logoAnimator.setDuration(750);
|
||||
ObjectAnimator sunAnimator = ObjectAnimator.ofFloat(sun, "alpha", 0, 1);
|
||||
sunAnimator.setInterpolator(new LinearInterpolator());
|
||||
sunAnimator.setDuration(150);
|
||||
@@ -105,6 +111,7 @@ public class SplashFragment extends Fragment {
|
||||
|
||||
set.playTogether(sunAnimator, titleAnimator, subtitleAnimator);
|
||||
set.play(worldAnimator).after(sunAnimator);
|
||||
set.play(logoAnimator).after(sunAnimator);
|
||||
set.play(gradientAnimator).after(sunAnimator);
|
||||
set.start();
|
||||
return root;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -12,7 +11,6 @@ import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavOptions;
|
||||
@@ -29,7 +27,7 @@ import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.databinding.FragmentStateBinding;
|
||||
import com.mowesta.android.app.model.AbstractPlaceViewModel;
|
||||
import com.mowesta.android.app.model.BindingTransforms;
|
||||
import com.mowesta.android.app.binding.BindingTransforms;
|
||||
import com.mowesta.android.app.model.StateViewModel;
|
||||
import com.mowesta.android.app.util.MapViewUtil;
|
||||
import com.mowesta.android.feign.model.State;
|
||||
@@ -108,7 +106,7 @@ public class StateFragment extends AbstractPlaceFragment {
|
||||
model.getCities().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
MapViewUtil.removePolylines(mapView, polylines);
|
||||
polylines.clear();
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuInflater;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
@@ -15,7 +11,6 @@ import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.Navigation;
|
||||
@@ -29,20 +24,12 @@ import com.google.android.material.bottomsheet.BottomSheetBehavior;
|
||||
import com.locoslab.android.leafless.MapView;
|
||||
import com.locoslab.android.leafless.marker.Marker;
|
||||
import com.locoslab.library.geometry.wgs.Coordinate;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.adapter.DiagramEntryPagedListAdapter;
|
||||
import com.mowesta.android.app.databinding.FragmentStateBinding;
|
||||
import com.mowesta.android.app.databinding.FragmentStationBinding;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.BindingTransforms;
|
||||
import com.mowesta.android.app.model.DiagramEntry;
|
||||
import com.mowesta.android.app.model.StateViewModel;
|
||||
import com.mowesta.android.app.model.StationViewModel;
|
||||
import com.mowesta.android.app.model.StationsViewModel;
|
||||
import com.mowesta.android.app.util.MapViewUtil;
|
||||
import com.mowesta.android.feign.model.State;
|
||||
import com.mowesta.android.feign.model.WeatherReport;
|
||||
import com.mowesta.android.feign.model.WeatherStation;
|
||||
|
||||
@@ -122,7 +109,7 @@ public class StationFragment extends AbstractDiagramFragment {
|
||||
model.getReports().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
if (model.getStation().getValue() != null) {
|
||||
WeatherStation s = model.getStation().getValue();
|
||||
@@ -169,8 +156,7 @@ public class StationFragment extends AbstractDiagramFragment {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUnitChanged() {
|
||||
super.onUnitChanged();
|
||||
public void onRefreshDiagram() {
|
||||
RecyclerView recyclerView = getView().findViewById(R.id.recycler);
|
||||
recyclerView.getAdapter().notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.content.res.Configuration;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -23,14 +24,33 @@ import com.mowesta.android.app.databinding.FragmentStationsBinding;
|
||||
import com.mowesta.android.app.databinding.ViewStationEntryBinding;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.model.StationsViewModel;
|
||||
import com.mowesta.android.app.util.TabletUtil;
|
||||
import com.mowesta.android.feign.model.WeatherStation;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Shows a list of the available stations.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class StationsFragment extends AbstractNetworkFragment {
|
||||
private RecyclerView recyclerView;
|
||||
|
||||
private void applyGridWidth() {
|
||||
if (!TabletUtil.isTablet(requireContext())) {
|
||||
return;
|
||||
}
|
||||
|
||||
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
|
||||
TabletUtil.setGridLayout(recyclerView, width);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(@NotNull Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
applyGridWidth();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractNetworkViewModel getNetworkViewModel() {
|
||||
@@ -50,7 +70,9 @@ public class StationsFragment extends AbstractNetworkFragment {
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
RecyclerView recycler = view.findViewById(R.id.recycler);
|
||||
recyclerView = view.findViewById(R.id.recycler);
|
||||
applyGridWidth();
|
||||
|
||||
StationsViewModel model = new ViewModelProvider(this).get(StationsViewModel.class);
|
||||
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
|
||||
StationEntryPagedListAdapter adapter = new StationEntryPagedListAdapter(getViewLifecycleOwner(), (station) -> {
|
||||
@@ -65,7 +87,7 @@ public class StationsFragment extends AbstractNetworkFragment {
|
||||
model.getStations().observe(getViewLifecycleOwner(), (list) -> {
|
||||
adapter.submitList(list);
|
||||
});
|
||||
recycler.setAdapter(adapter);
|
||||
recyclerView.setAdapter(adapter);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,7 +163,7 @@ public class StationsFragment extends AbstractNetworkFragment {
|
||||
* Creates a new paged list adapter that will inform
|
||||
* the listener about click events.
|
||||
*
|
||||
* @param owner The lifecycle owner.
|
||||
* @param owner The lifecycle owner.
|
||||
* @param listener The listener.
|
||||
*/
|
||||
public StationEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull StationsViewModel.OnStationSelectedListener listener) {
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
/**
|
||||
* A dialog that enables the user to select the temperature.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TemperatureUnitDialogFragment extends DialogFragment {
|
||||
|
||||
/**
|
||||
* The settings.
|
||||
*/
|
||||
private MowestaSettings settings;
|
||||
/**
|
||||
* The selected uni.
|
||||
*/
|
||||
private MowestaSettings.TemperatureUnit unit;
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
settings = new MowestaSettings(getActivity().getApplication());
|
||||
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getContext());
|
||||
builder.setIcon(R.drawable.ic_thermometer_normal_24);
|
||||
builder.setTitle(R.string.customize_hint_temperature);
|
||||
CharSequence[] items = new CharSequence[] {
|
||||
getString(R.string.customize_temperature_both),
|
||||
getString(R.string.customize_temperature_celsius),
|
||||
getString(R.string.customize_temperature_fahrenheit)
|
||||
};
|
||||
unit = settings.getTemperatureUnit();
|
||||
int select = unit.ordinal();
|
||||
builder.setSingleChoiceItems(items, select, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
MowestaSettings.TemperatureUnit[] v = MowestaSettings.TemperatureUnit.values();
|
||||
if (which >= 0 && which < v.length) {
|
||||
unit = v[which];
|
||||
}
|
||||
}
|
||||
});
|
||||
builder.setNeutralButton(android.R.string.cancel, (dialog, which) -> {
|
||||
dismiss();
|
||||
});
|
||||
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
|
||||
settings.setTemperatureUnit(unit);
|
||||
dismiss();
|
||||
});
|
||||
return builder.create();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
@@ -33,11 +34,14 @@ import androidx.navigation.Navigation;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter;
|
||||
import androidx.viewpager2.widget.ViewPager2;
|
||||
import androidx.webkit.WebViewAssetLoader;
|
||||
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.Button;
|
||||
@@ -66,7 +70,7 @@ public class TermsFragment extends Fragment {
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.setModel(model);
|
||||
binding.setContinueListener(() -> {
|
||||
MowestaSettings settings = new MowestaSettings(getActivity().getApplication());
|
||||
MowestaSettings settings = ((IApp)getContext().getApplicationContext()).getSettings();
|
||||
settings.markTermsAccepted();
|
||||
if (shouldShowLogin()) {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_terms_login);
|
||||
@@ -165,7 +169,9 @@ public class TermsFragment extends Fragment {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
int url = getArguments().getInt("url", 0);
|
||||
webView = (WebView) view.findViewById(R.id.web_view);
|
||||
webView.getSettings().setAllowFileAccessFromFileURLs(true);
|
||||
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
|
||||
.addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(view.getContext()))
|
||||
.build();
|
||||
webView.setWebViewClient(new WebViewClient() {
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
@@ -179,6 +185,20 @@ public class TermsFragment extends Fragment {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@RequiresApi(21)
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view,
|
||||
WebResourceRequest request) {
|
||||
return assetLoader.shouldInterceptRequest(request.getUrl());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation") // for API < 21
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
|
||||
return assetLoader.shouldInterceptRequest(Uri.parse(url));
|
||||
}
|
||||
|
||||
});
|
||||
if (url != 0) {
|
||||
webView.loadUrl(getResources().getString(url));
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
/**
|
||||
* A dialog fragment to enable the user to select the unit system.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class UnitSystemDialogFragment extends DialogFragment {
|
||||
|
||||
/**
|
||||
* The settings.
|
||||
*/
|
||||
private MowestaSettings settings;
|
||||
/**
|
||||
* The selected system.
|
||||
*/
|
||||
private MowestaSettings.UnitSystem system;
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
settings = new MowestaSettings(getActivity().getApplication());
|
||||
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getContext());
|
||||
builder.setIcon(R.drawable.ic_barometer_normal_24);
|
||||
builder.setTitle(R.string.customize_hint_system);
|
||||
CharSequence[] items = new CharSequence[] {
|
||||
getString(R.string.customize_system_both),
|
||||
getString(R.string.customize_system_standard),
|
||||
getString(R.string.customize_system_imperial)
|
||||
};
|
||||
system = settings.getUnitSystem();
|
||||
int select = system.ordinal();
|
||||
builder.setSingleChoiceItems(items, select, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
MowestaSettings.UnitSystem[] v = MowestaSettings.UnitSystem.values();
|
||||
if (which >= 0 && which < v.length) {
|
||||
system = v[which];
|
||||
}
|
||||
}
|
||||
});
|
||||
builder.setNeutralButton(android.R.string.cancel, (dialog, which) -> {
|
||||
dismiss();
|
||||
});
|
||||
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
|
||||
settings.setUnitSystem(system);
|
||||
dismiss();
|
||||
});
|
||||
return builder.create();
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,53 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageButton;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.android.exoplayer2.ExoPlayer;
|
||||
import com.google.android.exoplayer2.SimpleExoPlayer;
|
||||
import com.google.android.exoplayer2.database.DefaultDatabaseProvider;
|
||||
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
|
||||
import com.google.android.exoplayer2.MediaItem;
|
||||
import com.google.android.exoplayer2.ExoPlayer;
|
||||
import com.google.android.exoplayer2.source.MediaSource;
|
||||
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
|
||||
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
|
||||
import com.google.android.exoplayer2.ui.PlayerView;
|
||||
import com.google.android.exoplayer2.upstream.DataSource;
|
||||
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
|
||||
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
|
||||
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
|
||||
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
|
||||
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
|
||||
import com.google.android.exoplayer2.ui.StyledPlayerView;
|
||||
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
|
||||
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
|
||||
import com.google.android.exoplayer2.util.Util;
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.PreferenceLiveData;
|
||||
import com.mowesta.android.app.model.AbstractNetworkViewModel;
|
||||
import com.mowesta.android.app.task.ImageTask;
|
||||
import com.mowesta.android.app.util.ContentScaler;
|
||||
import com.mowesta.android.app.util.DateFormatter;
|
||||
import com.mowesta.android.app.util.MercatorPositioner;
|
||||
import com.mowesta.android.app.util.TimeUtils;
|
||||
import com.mowesta.android.app.view.MarkerView;
|
||||
import com.mowesta.android.app.view.WeatherView;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.WeatherVideo;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
@@ -55,7 +55,7 @@ import java.io.IOException;
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class VideoFragment extends Fragment {
|
||||
public class VideoFragment extends AbstractNetworkFragment {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
@@ -156,7 +156,7 @@ public class VideoFragment extends Fragment {
|
||||
/**
|
||||
* The handler for the timing.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The date formatter.
|
||||
@@ -186,7 +186,7 @@ public class VideoFragment extends Fragment {
|
||||
/**
|
||||
* The player.
|
||||
*/
|
||||
private PlayerView player;
|
||||
private StyledPlayerView player;
|
||||
|
||||
/**
|
||||
* The weather video to compute the timings.
|
||||
@@ -219,6 +219,11 @@ public class VideoFragment extends Fragment {
|
||||
};
|
||||
|
||||
|
||||
@Override
|
||||
protected AbstractNetworkViewModel getNetworkViewModel() {
|
||||
return new ViewModelProvider(this).get(ExoPlayerViewModel.class);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
@@ -227,15 +232,29 @@ public class VideoFragment extends Fragment {
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
model = new ViewModelProvider(this).get(ExoPlayerViewModel.class);
|
||||
ImageButton scaleButton = view.findViewById(R.id.video_scale);
|
||||
ImageButton zoomButton = view.findViewById(R.id.video_zoom);
|
||||
player = view.findViewById(R.id.video_view);
|
||||
player.setShowBuffering(PlayerView.SHOW_BUFFERING_ALWAYS);
|
||||
player.setShowBuffering(StyledPlayerView.SHOW_BUFFERING_ALWAYS);
|
||||
overlay = view.findViewById(R.id.video_time);
|
||||
marker = new MarkerView(view.getContext());
|
||||
marker.setLayoutParams(new FrameLayout.LayoutParams
|
||||
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
player.getOverlayFrameLayout().addView(marker);
|
||||
View frame = LayoutInflater.from(view.getContext()).inflate(R.layout.view_marker, player.getOverlayFrameLayout(), true);
|
||||
marker = frame.findViewById(R.id.video_marker);
|
||||
ImageView scaleImage = frame.findViewById(R.id.video_scale_image);
|
||||
View scaleBackground = frame.findViewById(R.id.video_scale_background);
|
||||
ImageButton scaleButton = view.findViewById(R.id.video_scale);
|
||||
scaleButton.setOnClickListener((v) -> {
|
||||
model.showScale.setValue(!model.showScale.getValue());
|
||||
});
|
||||
model.showScale.observe(getViewLifecycleOwner(), (v) -> {
|
||||
int visible = v?View.VISIBLE:View.GONE;
|
||||
scaleBackground.setVisibility(visible);
|
||||
scaleImage.setVisibility(visible);
|
||||
int img = v?R.drawable.ic_remove_circle_normal_24:R.drawable.ic_remove_circle_outline_normal_24;
|
||||
int txt = v?R.string.button_hide_scale:R.string.button_show_scale;
|
||||
scaleButton.setContentDescription(getString(txt));
|
||||
scaleButton.setImageResource(img);
|
||||
});
|
||||
Args args = Args.fromBundle(getArguments());
|
||||
if (args != null) {
|
||||
video = args.getVideo();
|
||||
@@ -252,33 +271,42 @@ public class VideoFragment extends Fragment {
|
||||
timeUtils = new TimeUtils(System.currentTimeMillis(), timezone);
|
||||
formatter = new DateFormatter(getContext());
|
||||
if (model.exoPlayer == null) {
|
||||
model.exoPlayer = new SimpleExoPlayer.Builder(getContext()).build();
|
||||
model.exoPlayer = new ExoPlayer.Builder(getContext()).build();
|
||||
model.scaler.setContent(video.getWidth(), video.getHeight());
|
||||
IApp app = (IApp)getActivity().getApplication();
|
||||
DataSource.Factory dataSourceFactory = new CacheDataSourceFactory
|
||||
(app.getMediaCache(), new DefaultHttpDataSourceFactory( Util.getUserAgent
|
||||
(getContext(), getContext().getPackageName()), null));
|
||||
MediaSource videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
|
||||
.createMediaSource(Uri.parse(video.getUrl()));
|
||||
model.exoPlayer.prepare(videoSource);
|
||||
DefaultHttpDataSource.Factory hf = new DefaultHttpDataSource.Factory();
|
||||
hf.setUserAgent(Util.getUserAgent(getContext(), getContext().getPackageName()));
|
||||
CacheDataSource.Factory cdf = new CacheDataSource.Factory();
|
||||
cdf.setUpstreamDataSourceFactory(hf);
|
||||
cdf.setCache(app.getMediaCache());
|
||||
MediaSource videoSource = new ProgressiveMediaSource.Factory(cdf)
|
||||
.createMediaSource(MediaItem.fromUri(video.getUrl()));
|
||||
model.exoPlayer.setMediaSource(videoSource);
|
||||
model.exoPlayer.prepare();
|
||||
model.exoPlayer.setPlayWhenReady(true);
|
||||
model.scaleUrl = video.getScale();
|
||||
model.reload();
|
||||
}
|
||||
player.setPlayer(model.exoPlayer);
|
||||
model.scaleImage.observe(getViewLifecycleOwner(), (b)-> {
|
||||
scaleImage.setImageBitmap(b);
|
||||
});
|
||||
|
||||
model.mode.observe(getViewLifecycleOwner(), (mode) -> {
|
||||
if (mode == ContentScaler.ScaleMode.FIT) {
|
||||
scaleButton.setImageResource(R.drawable.ic_zoom_out_map_normal_24);
|
||||
scaleButton.setContentDescription(getString(R.string.button_fill_screen));
|
||||
zoomButton.setImageResource(R.drawable.ic_zoom_out_map_normal_24);
|
||||
zoomButton.setContentDescription(getString(R.string.button_fill_screen));
|
||||
player.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
|
||||
} else {
|
||||
scaleButton.setImageResource(R.drawable.ic_aspect_ratio_normal_24);
|
||||
scaleButton.setContentDescription(getString(R.string.button_fit_screen));
|
||||
zoomButton.setImageResource(R.drawable.ic_aspect_ratio_normal_24);
|
||||
zoomButton.setContentDescription(getString(R.string.button_fit_screen));
|
||||
player.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
|
||||
}
|
||||
if (model.markerX != null && model.markerY != null) {
|
||||
updateVideo(marker.getWidth(), marker.getHeight());
|
||||
}
|
||||
});
|
||||
scaleButton.setOnClickListener((v) -> {
|
||||
zoomButton.setOnClickListener((v) -> {
|
||||
model.mode.setValue(model.mode.getValue() == ContentScaler.ScaleMode.FILL?
|
||||
ContentScaler.ScaleMode.FIT: ContentScaler.ScaleMode.FILL);
|
||||
});
|
||||
@@ -288,7 +316,8 @@ public class VideoFragment extends Fragment {
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
Window window = getActivity().getWindow();
|
||||
if (window != null) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
if (video != null) {
|
||||
handler.postDelayed(timer, 500);
|
||||
if (model.markerX != null && model.markerY != null) {
|
||||
@@ -303,7 +332,8 @@ public class VideoFragment extends Fragment {
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
Window window = getActivity().getWindow();
|
||||
if (window != null) window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
marker.removeOnLayoutChangeListener(markerListener);
|
||||
handler.removeCallbacks(timer);
|
||||
super.onPause();
|
||||
@@ -349,7 +379,7 @@ public class VideoFragment extends Fragment {
|
||||
* The view model to store the exo player instance when
|
||||
* the view is destroyed.
|
||||
*/
|
||||
public static class ExoPlayerViewModel extends AndroidViewModel {
|
||||
public static class ExoPlayerViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
/**
|
||||
* The exo player (initialized only once).
|
||||
@@ -361,6 +391,11 @@ public class VideoFragment extends Fragment {
|
||||
*/
|
||||
final MutableLiveData<ContentScaler.ScaleMode> mode = new MutableLiveData<>(ContentScaler.ScaleMode.FILL);
|
||||
|
||||
/**
|
||||
* A boolean preference to show the scale.
|
||||
*/
|
||||
final PreferenceLiveData showScale;
|
||||
|
||||
/**
|
||||
* The relative position of the marker in x.
|
||||
*/
|
||||
@@ -376,15 +411,39 @@ public class VideoFragment extends Fragment {
|
||||
*/
|
||||
final ContentScaler scaler = new ContentScaler();
|
||||
|
||||
/**
|
||||
* The scale image.
|
||||
*/
|
||||
final MutableLiveData<Bitmap> scaleImage = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The weather video's scale image.
|
||||
*/
|
||||
String scaleUrl;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a view model.
|
||||
*/
|
||||
public ExoPlayerViewModel(Application application) {
|
||||
super(application);
|
||||
MowestaSettings s = ((IApp)application).getSettings();
|
||||
showScale = new PreferenceLiveData(s.getPreferences(), MowestaSettings.SHOW_SCALE,
|
||||
s.getContext().getResources().getBoolean(R.bool.show_scale_defaut));
|
||||
mode.observeForever((m)->scaler.setMode(m));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
long requestCode = newRequestCode();
|
||||
scaleImage.setValue(null);
|
||||
if (scaleUrl != null) {
|
||||
new ImageTask((url, bitmap)-> {
|
||||
if (bitmap == null) finishRequest(requestCode, true);
|
||||
else completeRequest(requestCode, () -> scaleImage.setValue(bitmap));
|
||||
}).execute(scaleUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+10
-4
@@ -1,6 +1,7 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
@@ -16,6 +17,11 @@ import com.mowesta.android.app.repository.ClientFactory;
|
||||
*/
|
||||
public abstract class AbstractNetworkViewModel extends AndroidViewModel {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "NetworkViewModel";
|
||||
|
||||
/**
|
||||
* A class to store a parameter together with a request code.
|
||||
*
|
||||
@@ -87,15 +93,15 @@ public abstract class AbstractNetworkViewModel extends AndroidViewModel {
|
||||
*/
|
||||
public AbstractNetworkViewModel(@NonNull Application application) {
|
||||
super(application);
|
||||
this.requests.observeForever((v) -> printState());
|
||||
this.error.observeForever((v) -> printState());
|
||||
//this.requests.observeForever((v) -> printState());
|
||||
//this.error.observeForever((v) -> printState());
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the internal state of the model.
|
||||
*/
|
||||
private void printState() {
|
||||
System.out.println(getClass().getSimpleName() + " " + requestCode + " " + error.getValue() + " " + requests.getValue());
|
||||
Log.d(TAG, getClass().getSimpleName() + " " + requestCode + " " + error.getValue() + " " + requests.getValue());
|
||||
}
|
||||
|
||||
|
||||
@@ -181,7 +187,7 @@ public abstract class AbstractNetworkViewModel extends AndroidViewModel {
|
||||
this.requests.setValue(0);
|
||||
this.error.setValue(Boolean.FALSE);
|
||||
requestCode += 1;
|
||||
printState();
|
||||
//printState();
|
||||
return requestCode;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.google.android.exoplayer2.ExoPlayer;
|
||||
import com.google.android.exoplayer2.MediaItem;
|
||||
import com.google.android.exoplayer2.source.MediaSource;
|
||||
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
|
||||
import com.google.android.exoplayer2.upstream.AssetDataSource;
|
||||
import com.google.android.exoplayer2.upstream.DataSource;
|
||||
|
||||
public class AdvertiseViewModel extends AndroidViewModel {
|
||||
|
||||
private ExoPlayer exoPlayer;
|
||||
|
||||
private MutableLiveData<Boolean> close = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
private MutableLiveData<Boolean> open = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
public AdvertiseViewModel(Application app) {
|
||||
super(app);
|
||||
ExoPlayer.Builder builder = new ExoPlayer.Builder(app);
|
||||
exoPlayer = builder.build();
|
||||
DataSource.Factory df = new DataSource.Factory() {
|
||||
@Override
|
||||
public DataSource createDataSource() {
|
||||
return new AssetDataSource(app);
|
||||
}
|
||||
};
|
||||
MediaSource videoSource = new ProgressiveMediaSource.Factory(df)
|
||||
.createMediaSource(MediaItem.fromUri("android_assets:///dasfest.mp4"));
|
||||
exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ALL);
|
||||
exoPlayer.setMediaSource(videoSource);
|
||||
exoPlayer.prepare();
|
||||
exoPlayer.setPlayWhenReady(true);
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getClose() {
|
||||
return close;
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getOpen() {
|
||||
return open;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
close.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public void open() {
|
||||
open.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public ExoPlayer getExoPlayer() {
|
||||
return exoPlayer;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
exoPlayer.stop();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,16 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.DataSource;
|
||||
import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.CityPage;
|
||||
@@ -36,7 +32,7 @@ public class CitiesViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* A handler to run on the main thread.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates the view model.
|
||||
|
||||
@@ -11,8 +11,7 @@ import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.util.DateFormatter;
|
||||
import com.mowesta.android.app.util.TimeUtils;
|
||||
import com.mowesta.android.app.util.WeatherAggregate;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import org.geojson.Geometry;
|
||||
@@ -47,16 +46,17 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
void onStationSelected(WeatherStation station);
|
||||
}
|
||||
|
||||
/** The view types to navigate to. */
|
||||
public enum ForecastType { DAY, TIME, HOUR }
|
||||
|
||||
/**
|
||||
* A navigation request caused by a click on a summary.
|
||||
*/
|
||||
public static class NavigationRequest {
|
||||
/** The view types to navigate to. */
|
||||
public enum ListType { DAY, TIME, HOUR }
|
||||
|
||||
/** The list type to navigate to. */
|
||||
private @NonNull ListType type;
|
||||
private @NonNull
|
||||
ForecastType type;
|
||||
/** The condition to navigate to. */
|
||||
private @NonNull int position;
|
||||
|
||||
@@ -66,7 +66,7 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
* @param type The type.
|
||||
* @param position The position.
|
||||
*/
|
||||
public NavigationRequest(@NonNull ListType type, @NonNull int position) {
|
||||
public NavigationRequest(@NonNull ForecastType type, @NonNull int position) {
|
||||
this.type = type;
|
||||
this.position = position;
|
||||
}
|
||||
@@ -77,7 +77,7 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
* @return The type.
|
||||
*/
|
||||
@NonNull
|
||||
public ListType getType() {
|
||||
public ForecastType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
(input, status) -> { finishRequest(input, true); });
|
||||
|
||||
private final ApiTask<RequestParameter<Long>, List<WeatherVideo>> videoLoader = new ApiTask<>
|
||||
((input, client) -> client.getLatestCityVideos(input.getValue()),
|
||||
((input, client) -> client.getLatestCityVideos(input.getValue()),
|
||||
(input, result) -> { completeRequest(input, () -> videos.setValue(result)); },
|
||||
(input, status) -> { finishRequest(input, true); });
|
||||
|
||||
@@ -394,9 +394,9 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
*/
|
||||
private void updateVideos() {
|
||||
if (city.getValue() == null || videos.getValue() == null) {
|
||||
iconEurope.setValue(null);
|
||||
iconGlobal.setValue(null);
|
||||
cosmoEurope.setValue(null);
|
||||
iconEurope.setValue(new ArrayList<>());
|
||||
iconGlobal.setValue(new ArrayList<>());
|
||||
cosmoEurope.setValue(new ArrayList<>());
|
||||
} else {
|
||||
List<VideoViewModel> ieu = new ArrayList<>();
|
||||
List<VideoViewModel> igl = new ArrayList<>();
|
||||
@@ -441,86 +441,10 @@ public class CityViewModel extends AbstractPlaceViewModel {
|
||||
day.setValue(null);
|
||||
time.setValue(null);
|
||||
} else {
|
||||
DateFormatter df = new DateFormatter(getApplication());
|
||||
long now = System.currentTimeMillis();
|
||||
String tz = city.getValue().getTimezone();
|
||||
TimeUtils d = new TimeUtils(now, tz);
|
||||
List<WeatherCondition> wc = new ArrayList<>(forecast.getValue().getConditions());
|
||||
Collections.sort(wc, (a, b) -> (int)(a.getTime() - b.getTime()));
|
||||
List<ConditionViewModel> hours = new ArrayList<>();
|
||||
List<List<WeatherCondition>> days = new ArrayList<>();
|
||||
List<List<WeatherCondition>> times = new ArrayList<>();
|
||||
List<WeatherCondition> currentDay = null;
|
||||
List<WeatherCondition> currentTime = null;
|
||||
for (WeatherCondition c: wc) {
|
||||
long end = d.getEnd(c);
|
||||
ConditionViewModel vm = new ConditionViewModel(getApplication());
|
||||
long time = c.getTime();
|
||||
String title = d.getDayName(getApplication(), time);
|
||||
String subtitle = getApplication().getString(R.string.format_two_parts, df.asTime(time, tz), df.asDate(time, tz));
|
||||
vm.setData(title, subtitle, c, tz);
|
||||
hours.add(vm);
|
||||
if (currentDay == null) {
|
||||
currentDay = new ArrayList<>();
|
||||
currentDay.add(c);
|
||||
} else {
|
||||
if (d.isSameDay(d.getTime(currentDay), c.getTime())) {
|
||||
currentDay.add(c);
|
||||
} else {
|
||||
days.add(currentDay);
|
||||
currentDay = new ArrayList<>();
|
||||
currentDay.add(c);
|
||||
}
|
||||
}
|
||||
if (!d.isSameDay(d.getTime(currentDay), end)) {
|
||||
days.add(currentDay);
|
||||
currentDay = new ArrayList<>();
|
||||
currentDay.add(c);
|
||||
}
|
||||
if (currentTime == null) {
|
||||
currentTime = new ArrayList<>();
|
||||
currentTime.add(c);
|
||||
} else {
|
||||
if (d.isSameSlot(d.getTime(currentTime), c.getTime())) {
|
||||
currentTime.add(c);
|
||||
} else {
|
||||
times.add(currentTime);
|
||||
currentTime = new ArrayList<>();
|
||||
currentTime.add(c);
|
||||
}
|
||||
}
|
||||
if (!d.isSameSlot(d.getTime(currentTime), end)) {
|
||||
times.add(currentTime);
|
||||
currentTime = new ArrayList<>();
|
||||
currentTime.add(c);
|
||||
}
|
||||
}
|
||||
if (currentDay != null) days.add(currentDay);
|
||||
if (currentTime != null) times.add(currentTime);
|
||||
List<SummaryViewModel> models = new ArrayList<>();
|
||||
for (List<WeatherCondition> ds: days) {
|
||||
long time = d.getTime(ds);
|
||||
String title = d.getDayName(getApplication(), time);
|
||||
SummaryViewModel summary = new SummaryViewModel(getApplication());
|
||||
WeatherCondition[] data = new WeatherCondition[ds.size()];
|
||||
data = ds.toArray(data);
|
||||
summary.setData(title, getApplication().getString(R.string.label_full_day), data, tz);
|
||||
models.add(summary);
|
||||
}
|
||||
day.setValue(models);
|
||||
models = new ArrayList<>();
|
||||
for (List<WeatherCondition> ts: times) {
|
||||
long time = d.getTime(ts);
|
||||
String title = d.getDayName(getApplication(), time);
|
||||
int slot = d.getSlotName(time);
|
||||
SummaryViewModel summary = new SummaryViewModel(getApplication());
|
||||
WeatherCondition[] data = new WeatherCondition[ts.size()];
|
||||
data = ts.toArray(data);
|
||||
summary.setData(title, getApplication().getString(slot), data, tz);
|
||||
models.add(summary);
|
||||
}
|
||||
time.setValue(models);
|
||||
hour.setValue(hours);
|
||||
WeatherAggregate a = WeatherAggregate.getAggregate(getApplication(), city.getValue().getTimezone(), forecast.getValue().getConditions());
|
||||
hour.setValue(a.getHours());
|
||||
day.setValue(a.getDays());
|
||||
time.setValue(a.getTimes());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.graphics.Color;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.Observer;
|
||||
import androidx.lifecycle.ViewModel;
|
||||
|
||||
/**
|
||||
* The view model for the color picker dialog.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ColorViewModel extends ViewModel {
|
||||
|
||||
/**
|
||||
* The dialog state.
|
||||
*/
|
||||
public static enum State {
|
||||
/** The dialog is hidden. */
|
||||
HIDDEN,
|
||||
/** The dialog is visible. */
|
||||
VISIBLE,
|
||||
/** The dialog is confirmed. */
|
||||
CONFIRMED,
|
||||
/** The dialog is dismissed. */
|
||||
DISMISSED
|
||||
}
|
||||
|
||||
/** The red component from 0-255 */
|
||||
private final MutableLiveData<Float> red = new MutableLiveData<>(Float.valueOf(255));
|
||||
/** The green component from 0-255 */
|
||||
private final MutableLiveData<Float> green = new MutableLiveData<>(Float.valueOf(255));
|
||||
/** The blue component from 0-255 */
|
||||
private final MutableLiveData<Float> blue = new MutableLiveData<>(Float.valueOf(255));
|
||||
/** The computed color as RGB */
|
||||
private final MutableLiveData<Integer> color = new MutableLiveData<Integer>();
|
||||
/** The dialog state. */
|
||||
private final MutableLiveData<State> state = new MutableLiveData<>(State.HIDDEN);
|
||||
|
||||
/**
|
||||
* Creates a new model.
|
||||
*/
|
||||
public ColorViewModel() {
|
||||
Observer<Float> observer = (v) -> {
|
||||
color.setValue(Color.rgb(red.getValue().intValue(), green.getValue().intValue(), blue.getValue().intValue()));
|
||||
};
|
||||
red.observeForever(observer);
|
||||
green.observeForever(observer);
|
||||
blue.observeForever(observer);
|
||||
observer.onChanged(0f);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns live data with the state.
|
||||
*
|
||||
* @return The live data with the state.
|
||||
*/
|
||||
public LiveData<State> getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the color.
|
||||
*
|
||||
* @return The color.
|
||||
*/
|
||||
public LiveData<Integer> getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
/**
|
||||
* The blue component 0-255.
|
||||
*
|
||||
* @return The blue component.
|
||||
*/
|
||||
public MutableLiveData<Float> getBlue() {
|
||||
return blue;
|
||||
}
|
||||
|
||||
/**
|
||||
* The red component 0-255.
|
||||
*
|
||||
* @return The red component.
|
||||
*/
|
||||
public MutableLiveData<Float> getRed() {
|
||||
return red;
|
||||
}
|
||||
|
||||
/**
|
||||
* The green component 0-255.
|
||||
*
|
||||
* @return The green component.
|
||||
*/
|
||||
public MutableLiveData<Float> getGreen() {
|
||||
return green;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the color.
|
||||
*
|
||||
* @param rgb The rgb color.
|
||||
*/
|
||||
public void setColor(int rgb) {
|
||||
red.setValue(Float.valueOf((rgb >> 16) & 0xff));
|
||||
green.setValue(Float.valueOf((rgb >> 8) & 0xff));
|
||||
blue.setValue(Float.valueOf((rgb >> 0) & 0xff));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the dialog state.
|
||||
*
|
||||
* @param state The state.
|
||||
*/
|
||||
public void setState(State state) {
|
||||
this.state.setValue(state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import android.app.Application;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.arduino.ArduinoConfig;
|
||||
import com.mowesta.android.app.arduino.ConnectivityTask;
|
||||
import com.mowesta.android.app.arduino.NetworkTask;
|
||||
import com.mowesta.android.app.arduino.TransferTask;
|
||||
import com.mowesta.android.app.arduino.WifiTask;
|
||||
import com.mowesta.android.app.fragment.ConnectFragment;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.DeviceHandle;
|
||||
import com.mowesta.android.feign.model.DeviceInfo;
|
||||
|
||||
/**
|
||||
* The view model to configure a device.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ConnectViewModel extends AndroidViewModel {
|
||||
|
||||
/**
|
||||
* The state of the connection process.
|
||||
*/
|
||||
public enum State {
|
||||
/**
|
||||
* We are creating the device.
|
||||
*/
|
||||
DEVICE,
|
||||
/**
|
||||
* We are connecting to the network.
|
||||
*/
|
||||
NETWORK,
|
||||
/**
|
||||
* We are transferring the data to the station.
|
||||
*/
|
||||
CONFIGURE,
|
||||
/**
|
||||
* The process has been completed successfully.
|
||||
*/
|
||||
COMPLETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "ConnectViewModel";
|
||||
|
||||
/** The current state of the process. */
|
||||
final MutableLiveData<State> state = new MutableLiveData<>(null);
|
||||
|
||||
/** The text to display in the center of the screen. */
|
||||
final MutableLiveData<Integer> messageText = new MutableLiveData<>(R.string.connect_message_creating);
|
||||
|
||||
/** A flag to show the retry button. */
|
||||
final MutableLiveData<Boolean> retryVisible = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* The arguments of the connect fragment with the latitude, longitude,
|
||||
* ssid name and password.
|
||||
*/
|
||||
private ConnectFragment.Args arguments;
|
||||
|
||||
/**
|
||||
* The device handle that is created as the first step.
|
||||
*/
|
||||
private DeviceHandle deviceHandle;
|
||||
|
||||
/**
|
||||
* The network task that is created as the second step.
|
||||
*/
|
||||
private NetworkTask networkTask;
|
||||
|
||||
/**
|
||||
* The transfer task that is created as the third step.
|
||||
*/
|
||||
private TransferTask transferTask;
|
||||
|
||||
/** Flag to indicate whether the process is cancelled. */
|
||||
private boolean cancelled;
|
||||
|
||||
/** The task to create the device handle for the new device. */
|
||||
private ApiTask<Void, DeviceHandle> createDeviceTask = new ApiTask<>((input, client) -> {
|
||||
DeviceInfo info = new DeviceInfo();
|
||||
info.setOs(DeviceInfo.OsEnum.ARDUINO);
|
||||
info.setManufacturer(getApplication().getString(R.string.setup_device_manufacturer));
|
||||
info.setModel(arguments.getDevice());
|
||||
info.setDevice(getApplication().getString(R.string.setup_device_name_default));
|
||||
return client.createDevice(info);
|
||||
}, (input, result) -> {
|
||||
this.deviceHandle = result;
|
||||
if (cancelled) {
|
||||
deleteDevice();
|
||||
} else {
|
||||
this.state.setValue(State.NETWORK);
|
||||
retry();
|
||||
}
|
||||
}, (input, status) -> {
|
||||
messageText.setValue(R.string.connect_message_create_failed);
|
||||
retryVisible.setValue(Boolean.TRUE);
|
||||
});
|
||||
|
||||
/** The task to delete the device, if the view model is disposed without successful completion. */
|
||||
private ApiTask<Long, Long> deleteDeviceTask = new ApiTask<>((input, client) -> {
|
||||
client.deleteDevice(input);
|
||||
return input;
|
||||
}, (input, result) -> {
|
||||
Log.d(TAG, "Device " + result + " deleted successfully.");
|
||||
}, (input, status) -> {
|
||||
Log.d(TAG, "Failed to delete device " + input + ".");
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new view model.
|
||||
*
|
||||
* @param application The application.
|
||||
*/
|
||||
public ConnectViewModel(@NonNull Application application) {
|
||||
super(application);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text to display in the center of the screen.
|
||||
*
|
||||
* @return The text.
|
||||
*/
|
||||
public LiveData<Integer> getMessageText() {
|
||||
return messageText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the boolean to determine whether the retry button
|
||||
* is visible.
|
||||
*
|
||||
* @return The boolean with the visibility of the retry button.
|
||||
*/
|
||||
public LiveData<Boolean> getRetryVisible() {
|
||||
return retryVisible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the state.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public LiveData<State> getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the connect fragment to set the arguments configured
|
||||
* through the setup fragment.
|
||||
*
|
||||
* @param arguments The arguments
|
||||
*/
|
||||
public void init(ConnectFragment.Args arguments) {
|
||||
if (this.arguments == null) {
|
||||
this.arguments = arguments;
|
||||
state.setValue(State.DEVICE);
|
||||
retry();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the device handle.
|
||||
*
|
||||
* @return The device handle.
|
||||
*/
|
||||
public DeviceHandle getDeviceHandle() {
|
||||
return deviceHandle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the next step based on the current state
|
||||
* of the process.
|
||||
*/
|
||||
public void retry() {
|
||||
retryVisible.setValue(Boolean.FALSE);
|
||||
if (state.getValue() == State.DEVICE) {
|
||||
IApp app = (IApp)getApplication();
|
||||
messageText.setValue(R.string.connect_message_creating);
|
||||
createDeviceTask.execute(null, app.getClientFactory().createClient(app.getUserRepository().getCredentials().getValue()));
|
||||
} else if (state.getValue() == State.NETWORK) {
|
||||
messageText.setValue(R.string.connect_message_searching);
|
||||
NetworkTask.OnNetworkChangedListener listener = (value) -> {
|
||||
if (value) {
|
||||
state.setValue(State.CONFIGURE);
|
||||
retry();
|
||||
} else {
|
||||
state.setValue(State.NETWORK);
|
||||
stopTasks();
|
||||
messageText.setValue(R.string.connect_message_search_failed);
|
||||
retryVisible.setValue(true);
|
||||
}
|
||||
};
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
networkTask = new ConnectivityTask(getApplication(), listener);
|
||||
} else {
|
||||
networkTask = new WifiTask(getApplication(), listener);
|
||||
}
|
||||
} else if (state.getValue() == State.CONFIGURE) {
|
||||
messageText.setValue(R.string.connect_message_transfering);
|
||||
transferTask = new TransferTask(getApplication(), getConfig(), (success) -> {
|
||||
if (!success) {
|
||||
state.setValue(State.NETWORK);
|
||||
stopTasks();
|
||||
messageText.setValue(R.string.connect_message_transfer_failed);
|
||||
retryVisible.setValue(true);
|
||||
} else {
|
||||
state.setValue(State.COMPLETE);
|
||||
stopTasks();
|
||||
messageText.setValue(R.string.connect_message_success);
|
||||
}
|
||||
});
|
||||
transferTask.execute();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the arduino configuration.
|
||||
*
|
||||
* @return The arduino configuration.
|
||||
*/
|
||||
private ArduinoConfig getConfig() {
|
||||
return new ArduinoConfig
|
||||
(deviceHandle.getId(), deviceHandle.getToken(),
|
||||
arguments.getNetwork(), arguments.getPassword(),
|
||||
arguments.getLongitude(), arguments.getLatitude());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cancels any ongoing progress.
|
||||
*/
|
||||
private void stopTasks() {
|
||||
if (networkTask != null) {
|
||||
networkTask.cancel();
|
||||
networkTask = null;
|
||||
}
|
||||
if (transferTask != null) {
|
||||
transferTask.cancel();
|
||||
transferTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the device.
|
||||
*/
|
||||
private void deleteDevice() {
|
||||
if (deviceHandle != null) {
|
||||
IApp app = (IApp)getApplication();
|
||||
deleteDeviceTask.execute(deviceHandle.getId(), app.getClientFactory().createClient
|
||||
(app.getUserRepository().getCredentials().getValue()));
|
||||
deviceHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
super.onCleared();
|
||||
stopTasks();
|
||||
this.cancelled = true;
|
||||
if (state.getValue() != State.COMPLETE) {
|
||||
deleteDevice();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.app.Presentation;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.DataSource;
|
||||
@@ -14,10 +12,8 @@ import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
@@ -25,7 +21,6 @@ import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.CityPage;
|
||||
import com.mowesta.android.feign.model.Country;
|
||||
import com.mowesta.android.feign.model.LocationReference;
|
||||
import com.mowesta.android.feign.model.State;
|
||||
|
||||
import org.geojson.Geometry;
|
||||
|
||||
@@ -61,7 +56,7 @@ public class CountryViewModel extends AbstractPlaceViewModel {
|
||||
/**
|
||||
* The handler to run on main.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The loader for the country.
|
||||
|
||||
@@ -7,11 +7,11 @@ import android.content.res.Resources;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.preference.Preference;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.mowesta.android.app.MowestaSettings;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.adapter.EnumPreferenceLiveData;
|
||||
import com.mowesta.android.app.adapter.PreferenceLiveData;
|
||||
|
||||
/**
|
||||
@@ -19,6 +19,16 @@ import com.mowesta.android.app.adapter.PreferenceLiveData;
|
||||
*/
|
||||
public class CustomizeViewModel extends AndroidViewModel {
|
||||
|
||||
/**
|
||||
* The live data with the temperature unit.
|
||||
*/
|
||||
private final EnumPreferenceLiveData<MowestaSettings.TemperatureUnit> temperatureUnit;
|
||||
|
||||
/**
|
||||
* The live data with the unit system.
|
||||
*/
|
||||
private final EnumPreferenceLiveData<MowestaSettings.UnitSystem> unitSystem;
|
||||
|
||||
/**
|
||||
* The live data with the precipitation.
|
||||
*/
|
||||
@@ -59,6 +69,8 @@ public class CustomizeViewModel extends AndroidViewModel {
|
||||
super(application);
|
||||
Resources r = application.getResources();
|
||||
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);
|
||||
unitSystem = new EnumPreferenceLiveData<>(p, MowestaSettings.UnitSystem.class, MowestaSettings.UNIT_SYSTEM, MowestaSettings.UnitSystem.BOTH);
|
||||
temperatureUnit = new EnumPreferenceLiveData<>(p, MowestaSettings.TemperatureUnit.class, MowestaSettings.TEMPERATURE_UNIT, MowestaSettings.TemperatureUnit.BOTH);
|
||||
showPressure = new PreferenceLiveData(p, MowestaSettings.SHOW_PRESSURE, r.getBoolean(R.bool.show_pressure_default));
|
||||
showSnow = new PreferenceLiveData(p, MowestaSettings.SHOW_SNOW, r.getBoolean(R.bool.show_snow_default));
|
||||
showHumidity = new PreferenceLiveData(p, MowestaSettings.SHOW_HUMIDITY, r.getBoolean(R.bool.show_humidity_default));
|
||||
@@ -121,5 +133,21 @@ public class CustomizeViewModel extends AndroidViewModel {
|
||||
return showWind;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a live data object to configure the temperature unit.
|
||||
*
|
||||
* @return A live data object to get and configure the temperature unit.
|
||||
*/
|
||||
public EnumPreferenceLiveData<MowestaSettings.TemperatureUnit> getTemperatureUnit() {
|
||||
return temperatureUnit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a live data object to configure the unit system.
|
||||
*
|
||||
* @return A live data object to configure the unit system.
|
||||
*/
|
||||
public EnumPreferenceLiveData<MowestaSettings.UnitSystem> getUnitSystem() {
|
||||
return unitSystem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.icu.util.Measure;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.LiveData;
|
||||
@@ -12,6 +12,7 @@ import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.binding.DiagramEntry;
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
@@ -59,7 +60,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* The handler to run on main.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates a new view model.
|
||||
@@ -195,7 +196,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<Measurement>> callback) {
|
||||
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
|
||||
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(now, id, 0l, params.requestedStartPosition, params.requestedLoadSize ); },
|
||||
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
|
||||
(id, status) -> { finishRequest(requestCode, true); });
|
||||
if (isCurrentRequest(requestCode)) {
|
||||
@@ -210,7 +211,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<DiagramEntry<Measurement>> callback) {
|
||||
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.startPosition, params.loadSize ); },
|
||||
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(now, id, 0l, params.startPosition, params.loadSize ); },
|
||||
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()))); },
|
||||
(id, status) -> { finishRequest(requestCode, true); });
|
||||
if (id != null && credentials != null && isCurrentRequest(requestCode)) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.LiveData;
|
||||
@@ -13,11 +14,8 @@ import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
import com.mowesta.android.feign.model.DevicePage;
|
||||
import com.mowesta.android.feign.model.WeatherStation;
|
||||
import com.mowesta.android.feign.model.WeatherStationPage;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@@ -28,18 +26,6 @@ import java.util.ArrayList;
|
||||
*/
|
||||
public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
/**
|
||||
* A listener that is informed when a device is selected.
|
||||
*/
|
||||
public interface OnDeviceSelectedListener {
|
||||
|
||||
/**
|
||||
* Called when a device is selected.
|
||||
*
|
||||
* @param device The selected device.
|
||||
*/
|
||||
void onDeviceSelected(Device device);
|
||||
}
|
||||
|
||||
/**
|
||||
* The list with the user's devices.
|
||||
@@ -54,7 +40,7 @@ public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* The handler to debounce the updates to the search term.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates the view model.
|
||||
@@ -78,7 +64,7 @@ public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
}, config);
|
||||
builder.setFetchExecutor((r) -> handler.post(r));
|
||||
devices = builder.build();
|
||||
credentials.removeObserver((c) -> {
|
||||
credentials.observeForever((c) -> {
|
||||
reload();
|
||||
});
|
||||
}
|
||||
@@ -94,6 +80,7 @@ public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
error.setValue(false);
|
||||
PagedList<Device> list = devices.getValue();
|
||||
if (list != null) {
|
||||
list.getDataSource().invalidate();
|
||||
@@ -108,6 +95,14 @@ public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
return devices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a live data object to access the credentials.
|
||||
*
|
||||
* @return The credentials.
|
||||
*/
|
||||
public LiveData<UserCredentials> getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* A data source for the paging framework that loads the
|
||||
@@ -142,7 +137,12 @@ public class DevicesViewModel extends AbstractNetworkViewModel {
|
||||
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<Device> callback) {
|
||||
ApiTask<Void, DevicePage> task = new ApiTask<>((v, client) -> { return client.getCurrentUserDevices(0, params.requestedLoadSize ); },
|
||||
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements(), 0, page.getTotal())); },
|
||||
(v, status) -> { finishRequest(requestCode, true); });
|
||||
(v, status) -> {
|
||||
if (status == 403) {
|
||||
getApp().getUserRepository().login(getApp().getUserRepository().getCredentials().getValue());
|
||||
}
|
||||
finishRequest(requestCode, true);
|
||||
});
|
||||
if (isCurrentRequest(requestCode)) {
|
||||
if (credentials == null) {
|
||||
callback.onResult(new ArrayList<>(), 0, 0);
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
@@ -15,6 +14,7 @@ import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.LocationHierarchyPage;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@@ -51,13 +51,13 @@ public class DrawerViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* A handler to debounce the search.
|
||||
*/
|
||||
final Handler handler = new Handler();
|
||||
final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The task to perform the search.
|
||||
*/
|
||||
private ApiTask<RequestParameter<String>, LocationHierarchyPage> searchTask = new ApiTask<>((input, client) -> {
|
||||
return client.searchLocations(getLanguage(), input.getValue(), 0, 10, null);
|
||||
return client.searchLocations(getLanguage(), input.getValue(), null,0, 10);
|
||||
}, (input, result) -> {
|
||||
completeRequest(input, () -> {
|
||||
results.setValue(result);
|
||||
|
||||
@@ -12,9 +12,15 @@ import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
import com.mowesta.android.app.repository.UserRepository;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.task.RefreshTask;
|
||||
import com.mowesta.android.app.task.SyncTask;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.feign.model.LocationReference;
|
||||
import com.mowesta.android.feign.model.Settings;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -38,6 +44,55 @@ public class FavoritesViewModel extends AndroidViewModel {
|
||||
void onFavoriteSelected(Favorite favorite);
|
||||
}
|
||||
|
||||
/**
|
||||
*The task that applies reorderings to the backend.
|
||||
*/
|
||||
private ApiTask<List<Favorite>, Void> remoteReorderTask = new ApiTask<>((input, client)->{
|
||||
Settings settings = client.getCurrentUserSettings();
|
||||
List<LocationReference> oldReferences = settings.getLocations();
|
||||
List<LocationReference> newReferences = new ArrayList<>();
|
||||
for (Favorite f: input) {
|
||||
search: for (int i = 0; i < oldReferences.size(); i++) {
|
||||
LocationReference r = oldReferences.get(i);
|
||||
if (r.getType() == f.getType() && r.getId() != null && r.getId().equals(f.getId())) {
|
||||
newReferences.add(r);
|
||||
oldReferences.remove(i);
|
||||
break search;
|
||||
}
|
||||
}
|
||||
}
|
||||
newReferences.addAll(oldReferences);
|
||||
settings.setLocations(newReferences);
|
||||
client.setCurrentUserSettings(settings);
|
||||
return null;
|
||||
},(input, output)->{
|
||||
// nothing to do
|
||||
}, (input, status)->{
|
||||
// ignore for now
|
||||
});
|
||||
|
||||
/**
|
||||
* The tasks that performs a local reordering in the database.
|
||||
*/
|
||||
private DatabaseTask<FavoriteDatabase, List<Favorite>, Void> localReoderTask = new DatabaseTask<>(
|
||||
(list, database) -> {
|
||||
database.runInTransaction(() -> {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Favorite input = list.get(i);
|
||||
Favorite target = database.getAccessor().findById(input.getType(), input.getId());
|
||||
if (target != null && !target.isDeleted()) {
|
||||
target.setPosition(i);
|
||||
database.getAccessor().update(target);
|
||||
}
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}, (input, output) -> {
|
||||
updateRemote(input);
|
||||
});
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The live data list of favorites from the database.
|
||||
*/
|
||||
@@ -130,4 +185,26 @@ public class FavoritesViewModel extends AndroidViewModel {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the order of the favorites locally and remotely.
|
||||
*
|
||||
* @param favorites The favorites.
|
||||
*/
|
||||
public void updateFavorites(List<Favorite> favorites) {
|
||||
localReoderTask.execute(favorites, getFavoriteDatabase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the favorites remotely.
|
||||
*
|
||||
* @param favorites The favorites.
|
||||
*/
|
||||
private void updateRemote(List<Favorite> favorites) {
|
||||
UserCredentials c = getUserRepository().getCredentials().getValue();
|
||||
if (c != null) {
|
||||
remoteReorderTask.execute(favorites, getApp().getClientFactory().createClient(c));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.graphics.Color;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.CityPage;
|
||||
import com.mowesta.android.feign.model.LocationReference;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A view model for a forecast widget. It provides possibilities to search for cities with a term
|
||||
* and a list of favorites.
|
||||
*
|
||||
* @author Johannes
|
||||
*/
|
||||
public class ForecastWidgetViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "ForecastWidgetViewModel";
|
||||
|
||||
/**
|
||||
* A handler to post updates.
|
||||
*/
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/** A flag to indicate whether the submit button can be pressed. */
|
||||
private final MutableLiveData<Boolean> valid = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/** The selected city, once the submit button has been pressed. */
|
||||
private final MutableLiveData<City> finished = new MutableLiveData<>(null);
|
||||
|
||||
/** The search term. */
|
||||
private final MutableLiveData<String> term = new MutableLiveData<>("");
|
||||
|
||||
/** The currently selected city. */
|
||||
private final MutableLiveData<City> selection = new MutableLiveData<>(null);
|
||||
|
||||
/** The cities that are displayed in the list. */
|
||||
private final MutableLiveData<List<City>> cities = new MutableLiveData<>(new ArrayList<>());
|
||||
|
||||
/** A boolean to indicate the temperature scale. */
|
||||
private final MutableLiveData<Boolean> celsius = new MutableLiveData<>(Boolean.TRUE);
|
||||
|
||||
/** The color for the widget. */
|
||||
private final MutableLiveData<Integer> color = new MutableLiveData<>(Color.rgb(255, 255, 255));
|
||||
|
||||
/** A boolean to indicate that the dialog should be opened. */
|
||||
private final MutableLiveData<Boolean> dialog = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/** The favorites of the user that are displayed, if there is no search term. */
|
||||
private final MutableLiveData<List<City>> favorites = new MutableLiveData<>(new ArrayList<>());
|
||||
|
||||
private ApiTask<RequestParameter<String>, CityPage> searchTask = new ApiTask<>(
|
||||
(input, client) -> {
|
||||
CityPage cities = client.searchCities(getApplication().getString(R.string.language_code), input.getValue(), null, 0, 20);
|
||||
return cities;
|
||||
},
|
||||
(input, result) -> {
|
||||
completeRequest(input, () -> cities.setValue(result.getElements()));
|
||||
},
|
||||
(input, status) -> {
|
||||
finishRequest(input, true);
|
||||
});
|
||||
|
||||
private DatabaseTask<FavoriteDatabase, Void, List<City>> favoritesTask = new DatabaseTask<>((input, database)-> {
|
||||
List<Favorite> fs = database.getAccessor().getActive(LocationReference.TypeEnum.CITY.ordinal());
|
||||
List<City> rs = new ArrayList<>();
|
||||
for (Favorite f: fs) {
|
||||
City c = f.getCity();
|
||||
if (c != null) rs.add(c);
|
||||
}
|
||||
return rs;
|
||||
}, (input, output) -> {
|
||||
favorites.setValue(output);
|
||||
if (term.getValue().length() == 0) {
|
||||
cities.setValue(output);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates a new view model.
|
||||
*
|
||||
* @param application The application.
|
||||
*/
|
||||
public ForecastWidgetViewModel(@NonNull Application application) {
|
||||
super(application);
|
||||
term.observeForever(v -> executeSearch(v));
|
||||
selection.observeForever(v -> valid.setValue(v != null));
|
||||
favoritesTask.execute(null, getApp().getFavoriteRepository().getDatabase());
|
||||
}
|
||||
|
||||
/*
|
||||
public LiveData<LocationHierarchyPage> getResults() {
|
||||
return results;
|
||||
}*/
|
||||
|
||||
public MutableLiveData<String> getTerm() {
|
||||
return term;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
this.term.setValue(term.getValue());
|
||||
}
|
||||
|
||||
private void executeSearch(final String term) {
|
||||
long code = newRequestCode();
|
||||
selection.setValue(null);
|
||||
if (term.length() == 0) {
|
||||
cities.setValue(favorites.getValue());
|
||||
} else if (term.length() < 3) {
|
||||
cities.setValue(new ArrayList<>());
|
||||
} else {
|
||||
cities.setValue(new ArrayList<>());
|
||||
startRequest(code);
|
||||
handler.postDelayed(() -> {
|
||||
if (isCurrentRequest(code)) {
|
||||
searchTask.execute(new RequestParameter<>(code, term), getClientFactory().createClient());
|
||||
}
|
||||
}, 250);
|
||||
}
|
||||
}
|
||||
|
||||
public MutableLiveData<List<City>> getCities() {
|
||||
return cities;
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getCelsius() {
|
||||
return celsius;
|
||||
}
|
||||
|
||||
public MutableLiveData<City> getFinished() {
|
||||
return finished;
|
||||
}
|
||||
|
||||
public MutableLiveData<City> getSelection() {
|
||||
return selection;
|
||||
}
|
||||
|
||||
public MutableLiveData<Integer> getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getDialog() {
|
||||
return dialog;
|
||||
}
|
||||
|
||||
public void setCelsius(boolean value) {
|
||||
this.celsius.setValue(value);
|
||||
}
|
||||
|
||||
public void onSave() {
|
||||
City c = selection.getValue();
|
||||
if (c != null) {
|
||||
finished.setValue(c);
|
||||
}
|
||||
}
|
||||
|
||||
public void onColor() {
|
||||
dialog.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
private static CityPage emptyPage() {
|
||||
CityPage result = new CityPage();
|
||||
result.setElements(Collections.emptyList());
|
||||
result.setTotal(0);
|
||||
result.setOffset(0);
|
||||
result.setSize(20);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +1,10 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.content.Context;
|
||||
import android.location.Location;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.BindingAdapter;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.feign.model.LocationHierarchy;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The view model for a location view.
|
||||
*/
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
@@ -10,11 +11,14 @@ import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.repository.DeviceRepository;
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
import com.mowesta.android.app.repository.UserRepository;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.RefreshTask;
|
||||
import com.mowesta.android.app.task.SyncTask;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
import com.mowesta.android.feign.model.DeviceHandle;
|
||||
@@ -114,8 +118,11 @@ public class LoginViewModel extends AndroidViewModel {
|
||||
info.setOs(DeviceInfo.OsEnum.ANDROID);
|
||||
return client.createDevice(info);
|
||||
}, (input, result) -> {
|
||||
if (input != null) getUserRepository().setCredentials(input);
|
||||
getDeviceRepository().setDevice(result);
|
||||
if (input != null) {
|
||||
getUserRepository().setCredentials(input);
|
||||
syncFavorites();
|
||||
}
|
||||
destination.setValue(Destination.COLLECTION);
|
||||
}, (input, status) -> {
|
||||
checking.setValue(false);
|
||||
@@ -135,6 +142,7 @@ public class LoginViewModel extends AndroidViewModel {
|
||||
getUserRepository().setCredentials((UserCredentials)input[0]);
|
||||
getDeviceRepository().setDevice(result);
|
||||
destination.setValue(Destination.DEVICES);
|
||||
syncFavorites();
|
||||
}, (input, status) -> {
|
||||
checking.setValue(false);
|
||||
if (status == 403) {
|
||||
@@ -144,7 +152,6 @@ public class LoginViewModel extends AndroidViewModel {
|
||||
} else {
|
||||
failure.setValue(R.string.login_failure_network);
|
||||
}
|
||||
System.out.println("Failure is: " + status);
|
||||
});
|
||||
|
||||
|
||||
@@ -155,6 +162,7 @@ public class LoginViewModel extends AndroidViewModel {
|
||||
(input, result)-> {
|
||||
getUserRepository().setCredentials(input);
|
||||
destination.setValue(Destination.DEVICES);
|
||||
syncFavorites();
|
||||
}, (input, status) -> {
|
||||
checking.setValue(false);
|
||||
if (status == 403) {
|
||||
@@ -449,5 +457,27 @@ public class LoginViewModel extends AndroidViewModel {
|
||||
}
|
||||
|
||||
|
||||
private FavoriteDatabase getFavoriteDatabase() {
|
||||
return ((IApp)getApplication()).getFavoriteRepository().getDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers the synchronization of the favorites.
|
||||
*/
|
||||
private void syncFavorites() {
|
||||
Log.d("LoginViewModel", "Syncing favorites.");
|
||||
UserCredentials credentials = getUserRepository().getCredentials().getValue();
|
||||
DefaultApi api = getClientFactory().createClient(credentials);
|
||||
RefreshTask refreshTask = new RefreshTask(getFavoriteDatabase(), (success)-> {
|
||||
Log.d("LoginViewModel", "Refresh complete: " + success);
|
||||
});
|
||||
SyncTask syncTask = new SyncTask(getFavoriteDatabase(), (success)-> {
|
||||
Log.d("LoginViewModel", "Sync complete: " + success);
|
||||
refreshTask.execute(api);
|
||||
});
|
||||
syncTask.execute(api);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.graphics.Color;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.feign.model.Device;
|
||||
|
||||
/**
|
||||
* The view model to configure a measure widget.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasureWidgetViewModel extends DevicesViewModel {
|
||||
|
||||
|
||||
/** A flag to indicate whether the submit button can be pressed. */
|
||||
private final MutableLiveData<Boolean> valid = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/** The selected device, once the submit button has been pressed. */
|
||||
private final MutableLiveData<Device> finished = new MutableLiveData<>(null);
|
||||
|
||||
/** A flag to indicate that the user pressed the login button. */
|
||||
private final MutableLiveData<Boolean> login = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/** The currently selected device. */
|
||||
private final MutableLiveData<Device> selection = new MutableLiveData<>(null);
|
||||
|
||||
/** A boolean to indicate the temperature scale. */
|
||||
private final MutableLiveData<Boolean> celsius = new MutableLiveData<>(Boolean.TRUE);
|
||||
|
||||
/** A boolean to indicate the temperature scale. */
|
||||
private final MutableLiveData<Boolean> si = new MutableLiveData<>(Boolean.TRUE);
|
||||
|
||||
/** The color for the widget. */
|
||||
private final MutableLiveData<Integer> color = new MutableLiveData<>(Color.rgb(255, 255, 255));
|
||||
|
||||
/** A boolean to indicate that the dialog should be opened. */
|
||||
private final MutableLiveData<Boolean> dialog = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* Creates the view model.
|
||||
*
|
||||
* @param application The application.
|
||||
*/
|
||||
public MeasureWidgetViewModel(@NonNull Application application) {
|
||||
super(application);
|
||||
selection.observeForever(v -> valid.setValue(v != null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the user presses the save button.
|
||||
*/
|
||||
public void onSave() {
|
||||
Device d = selection.getValue();
|
||||
if (d != null) {
|
||||
finished.setValue(d);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called if the user pressed the login button.
|
||||
*/
|
||||
public void onLogin() {
|
||||
login.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public void setCelsius(boolean value) {
|
||||
this.celsius.setValue(value);
|
||||
}
|
||||
|
||||
public void setSi(boolean value) {
|
||||
this.si.setValue(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the unit system.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getSi() {
|
||||
return si;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the temperature unit.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getCelsius() {
|
||||
return celsius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the model validity.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the selected device.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Device> getSelection() {
|
||||
return selection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the final selection.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Device> getFinished() {
|
||||
return finished;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the final selection.
|
||||
*
|
||||
* @return The live data.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getLogin() { return login; }
|
||||
|
||||
/**
|
||||
* Returns the current color.
|
||||
*
|
||||
* @return The color.
|
||||
*/
|
||||
public MutableLiveData<Integer> getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a boolean to signal that the color picker shall be opened.
|
||||
*
|
||||
* @return The dialog state.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getDialog() {
|
||||
return dialog;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the color button is pressed.
|
||||
*/
|
||||
public void onColor() {
|
||||
dialog.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -9,244 +8,21 @@ import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.mowesta.android.app.binding.MeasurementType;
|
||||
import com.mowesta.android.app.binding.MeasurementValue;
|
||||
import com.mowesta.android.feign.model.Measurement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The view model to display a single measurement
|
||||
* in a bottom sheet dialog.
|
||||
* The view model to display a single measurement in a bottom sheet dialog.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasurementViewModel extends AndroidViewModel {
|
||||
|
||||
|
||||
/**
|
||||
* The types of measurement context.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
public enum MeasurementType {
|
||||
|
||||
/**
|
||||
* A boolean to identify whether the battery is charging.
|
||||
* e.g. true false
|
||||
*/
|
||||
BATTERY_CHARGING(Boolean.class),
|
||||
|
||||
/**
|
||||
* The temperature reading of the battery (double value in centigrade, can be read through ACTION_BATTERY_CHANGED).
|
||||
* e.g. 37.1, -1.3
|
||||
*/
|
||||
BATTERY_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* A temperature reading of a temperature sensor (double value in centigrade, TYPE_TEMERATURE on Android).
|
||||
* e.g. 37.1, -1.3
|
||||
*/
|
||||
SENSOR_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* A pressure reading of a barometer sensor (double value in hPa, TYPE_BAROMETER on Android).
|
||||
* e.g. 1000.0, 998.26127
|
||||
*/
|
||||
SENSOR_PRESSURE(Double.class),
|
||||
|
||||
/**
|
||||
* A humidity reading of a humidity sensor (double value as relative humidity in %, TYPE_RELATIVE_HUMIDITY on Android).
|
||||
* range: 0-1 (0->0%, 1->100%, 0.5->50%)
|
||||
*/
|
||||
SENSOR_HUMIDITY(Double.class),
|
||||
|
||||
/**
|
||||
* The temperature of the cpu (double value in centigrade, can be read by analyzing the proc file system).
|
||||
* e.g. 37.1 -1.3
|
||||
*/
|
||||
CPU_TEMPERATURE(Double.class),
|
||||
|
||||
/**
|
||||
* The current frequency of the cpu (double value in mhz, can be read by analyzing the proc file system).
|
||||
*/
|
||||
CPU_FREQUENCY(Double.class),
|
||||
|
||||
/**
|
||||
* A boolean to determine whether the screen is on (true) or off (false).
|
||||
*/
|
||||
SCREEN_ENABLED(Boolean.class),
|
||||
|
||||
/**
|
||||
* The voltage of the battery (used to monitor the battery of the weather station).
|
||||
* e.g. 3.77 -> 3.77 Volt
|
||||
*/
|
||||
BATTERY_VOLTAGE(Double.class),
|
||||
|
||||
/**
|
||||
* The voltage of the solar panel (used to estimate whether the weather station is located in the sun).
|
||||
* e.g. 3.77 -> 3.77 Volt
|
||||
*/
|
||||
SOLAR_VOLTAGE(Double.class);
|
||||
|
||||
/**
|
||||
* The data type.
|
||||
*/
|
||||
private Class<?> type;
|
||||
|
||||
/**
|
||||
* Creates a measurement type with the specified data type.
|
||||
*
|
||||
* @param type The data type expected for the measurement.
|
||||
*/
|
||||
private MeasurementType(Class<?> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data type.
|
||||
*
|
||||
* @return The data type.
|
||||
*/
|
||||
public Class<?> getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the data and returns a java array with the type
|
||||
* represented by this constant or an empty array, if the
|
||||
* data cannot be parsed.
|
||||
*
|
||||
* @param value The value to parse.
|
||||
* @return The java object.
|
||||
*/
|
||||
public Object[] getValues(String value) {
|
||||
List<Object> result = new ArrayList<>();
|
||||
if (value != null) {
|
||||
String[] substrings = value.split(",");
|
||||
if (type == Boolean.class) {
|
||||
for (String s: substrings) {
|
||||
Boolean b = (Boolean)parseValue(s);
|
||||
if (b != null) result.add(b);
|
||||
}
|
||||
} else if (type == Double.class) {
|
||||
for (String s: substrings) {
|
||||
Double d = (Double)parseValue(s);
|
||||
if (d != null) result.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.toArray(new Object[result.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a single value.
|
||||
*
|
||||
* @param value The string value.
|
||||
* @return The parsed value.
|
||||
*/
|
||||
private Object parseValue(String value) {
|
||||
if (value == null) return null;
|
||||
value = value.trim();
|
||||
if (type == Boolean.class) {
|
||||
if ("true".equalsIgnoreCase(value)) return Boolean.TRUE;
|
||||
if ("false".equalsIgnoreCase(value)) return Boolean.FALSE;
|
||||
return null;
|
||||
} else if (type == Double.class) {
|
||||
try {
|
||||
return Double.valueOf(Double.parseDouble(value));
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Represents a single measurement value.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class MeasurementValue {
|
||||
|
||||
/**
|
||||
* The log tag.
|
||||
*/
|
||||
private static final String TAG = "MeasurementValue";
|
||||
|
||||
/**
|
||||
* The measurement type.
|
||||
*/
|
||||
private @NonNull MeasurementType type;
|
||||
|
||||
/**
|
||||
* The measurement value.
|
||||
*/
|
||||
private @Nullable String value;
|
||||
|
||||
/**
|
||||
* The extracted values.
|
||||
*/
|
||||
private @NonNull Object[] values;
|
||||
|
||||
public MeasurementValue(@NonNull MeasurementType type, @Nullable String value) {
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
this.values = parseValues();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to parse the value based on the type.
|
||||
*
|
||||
* @return The values.
|
||||
*/
|
||||
private @NonNull Object[] parseValues() {
|
||||
try {
|
||||
return type.getValues(value);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to parse " + type.name() + " from '" + value + "'.", e);
|
||||
return new Object[0];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the type.
|
||||
*
|
||||
* @return The type.
|
||||
*/
|
||||
@NonNull
|
||||
public MeasurementType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value(s).
|
||||
*
|
||||
* @return The values.
|
||||
*/
|
||||
@NonNull
|
||||
public Object[] getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this value has at
|
||||
* least one data item.
|
||||
*
|
||||
* @return True if the value has at least one data item..
|
||||
*/
|
||||
public boolean hasValue() {
|
||||
return values.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The measurement.
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -9,16 +8,8 @@ import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import com.mowesta.android.feign.model.Measurement;
|
||||
import com.mowesta.android.feign.model.WeatherReport;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The view model to display a single weather report
|
||||
* in a bottom sheet dialog.
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.os.ConfigurationCompat;
|
||||
import androidx.core.os.LocaleListCompat;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.Observer;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.fragment.ConnectFragment;
|
||||
import com.mowesta.android.app.util.PermissionUtil;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The view model to setup an adruino weather station.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class SetupViewModel extends AndroidViewModel {
|
||||
|
||||
/**
|
||||
* The gps status returned when registering a receiver.
|
||||
*/
|
||||
public enum GpsStatus {
|
||||
/** Gps registered. */
|
||||
SUCCESS,
|
||||
/** Gps permission missing. */
|
||||
PROHIBITED,
|
||||
/** Gps disabled. */
|
||||
DISABLED,
|
||||
}
|
||||
|
||||
/**
|
||||
* The view model.
|
||||
*/
|
||||
private static final String TAG = "SetupViewModel";
|
||||
|
||||
/**
|
||||
* The network name.
|
||||
*/
|
||||
final MutableLiveData<String> networkName = new MutableLiveData<>("");
|
||||
|
||||
/**
|
||||
* The validation status of the network name.
|
||||
*/
|
||||
final MutableLiveData<FormStatus> networkNameStatus = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The network password.
|
||||
*/
|
||||
final MutableLiveData<String> networkPassword = new MutableLiveData<>("");
|
||||
|
||||
/**
|
||||
* The validation status of the password.
|
||||
*/
|
||||
final MutableLiveData<FormStatus> networkPasswordStatus = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The device name.
|
||||
*/
|
||||
final MutableLiveData<String> deviceName = new MutableLiveData<>("");
|
||||
|
||||
/**
|
||||
* The validation status of the device name.
|
||||
*/
|
||||
final MutableLiveData<FormStatus> deviceNameStatus = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The longitude as string when entered manually.
|
||||
*/
|
||||
final MutableLiveData<String> longitude = new MutableLiveData<>("");
|
||||
|
||||
/**
|
||||
* The validation status of the longitude.
|
||||
*/
|
||||
final MutableLiveData<FormStatus> longitudeStatus = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The latitude as string when entered manually.
|
||||
*/
|
||||
final MutableLiveData<String> latitude = new MutableLiveData<>("");
|
||||
|
||||
/**
|
||||
* The validation status of the latitude when entered manually.
|
||||
*/
|
||||
final MutableLiveData<FormStatus> latitudeStatus = new MutableLiveData<>();
|
||||
|
||||
/**
|
||||
* The boolean to store whether the user wants to enter the position manually.
|
||||
*/
|
||||
final MutableLiveData<Boolean> manualPosition = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* The boolean to determine whether a gps receiver is registered.
|
||||
*/
|
||||
final MutableLiveData<Boolean> gpsRegistered = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* The boolean to store whether the user can press the gps button. This is
|
||||
* only enabled, when the user is not using a manual position and the gps
|
||||
* is not yet registered.
|
||||
*/
|
||||
final MutableLiveData<Boolean> gpsEnabled = new MutableLiveData<>(Boolean.TRUE);
|
||||
|
||||
/**
|
||||
* The validation status of the whole form.
|
||||
*/
|
||||
final MutableLiveData<Boolean> valid = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* A flag to indicate whether the animation should be played. This is used
|
||||
* to ensure that the "over the top" animation is only played when the view
|
||||
* model is new.
|
||||
*/
|
||||
private boolean animate = true;
|
||||
|
||||
/**
|
||||
* The location listener to receive location updates.
|
||||
*/
|
||||
final LocationListener locationListener = new LocationListener() {
|
||||
@Override
|
||||
public void onLocationChanged(Location location) {
|
||||
if (location.getAccuracy() < 100) {
|
||||
latitude.setValue(SetupViewModel.this.toString(location.getLatitude()));
|
||||
longitude.setValue(SetupViewModel.this.toString(location.getLongitude()));
|
||||
unregisterGpsReciever();
|
||||
}
|
||||
}
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) { }
|
||||
@Override
|
||||
public void onProviderEnabled(String provider) { }
|
||||
@Override
|
||||
public void onProviderDisabled(String provider) { }
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates the view model.
|
||||
*
|
||||
* @param application The application.
|
||||
*/
|
||||
public SetupViewModel(@NonNull Application application) {
|
||||
super(application);
|
||||
Observer<Boolean> gpsEnabledListener = (b) -> { gpsEnabled.setValue(!gpsRegistered.getValue() && !manualPosition.getValue()); };
|
||||
manualPosition.observeForever(gpsEnabledListener);
|
||||
manualPosition.observeForever((v) -> { if (v) unregisterGpsReciever(); });
|
||||
gpsRegistered.observeForever(gpsEnabledListener);
|
||||
networkName.observeForever((v) -> { validateNetworkName(); validate(); });
|
||||
networkPassword.observeForever((v) -> { validateNetworkPassword(); validate(); });
|
||||
deviceName.observeForever((v) -> { validateDeviceName(); validate(); });
|
||||
manualPosition.observeForever((v) -> { validateLatitude(); validateLongitude(); validate(); });
|
||||
longitude.observeForever((v) -> { validateLongitude(); validate(); });
|
||||
latitude.observeForever((v) -> { validateLatitude(); validate(); });
|
||||
deviceName.setValue(application.getString(R.string.setup_device_name_default));
|
||||
networkName.setValue(loadNetworkName(application));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to get the current wifi network name to which the device is connected
|
||||
* or returns an empty string, if this is not possible.
|
||||
*
|
||||
* @param application The applicaiton.
|
||||
* @return The network name.
|
||||
*/
|
||||
private String loadNetworkName(Application application) {
|
||||
try {
|
||||
String result = "";
|
||||
WifiManager manager = (WifiManager)application.getSystemService(Context.WIFI_SERVICE);
|
||||
if (manager != null) {
|
||||
WifiInfo info = manager.getConnectionInfo();
|
||||
if (info != null) {
|
||||
String ssid = info.getSSID();
|
||||
if (ssid != null && ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
|
||||
result = ssid.substring(1, ssid.length() - 1);
|
||||
} else {
|
||||
Log.d(TAG, "Ignoring invalid ssid: " + ssid);
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Failed to get connection info.");
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Failed to find wifi manager.");
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
Log.d(TAG, "Failed to load network.", e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the live data with the network name.
|
||||
*
|
||||
* @return The live data with the network name.
|
||||
*/
|
||||
public MutableLiveData<String> getNetworkName() {
|
||||
return networkName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the status for the network name.
|
||||
*
|
||||
* @return The live data with the status for the network name.
|
||||
*/
|
||||
public LiveData<FormStatus> getNetworkNameStatus() {
|
||||
return networkNameStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the network name.
|
||||
*/
|
||||
private void validateNetworkName() {
|
||||
String string = networkName.getValue();
|
||||
if (string == null || string.length() == 0) {
|
||||
networkNameStatus.setValue(new FormStatus(R.string.setup_error_wlan_name_too_short));
|
||||
} else {
|
||||
networkNameStatus.setValue(FormStatus.VALID);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the live data with the network password.
|
||||
*
|
||||
* @return The live data with the network password.
|
||||
*/
|
||||
public MutableLiveData<String> getNetworkPassword() {
|
||||
return networkPassword;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the status for the network password.
|
||||
*
|
||||
* @return The live data with the status for the network password.
|
||||
*/
|
||||
public LiveData<FormStatus> getNetworkPasswordStatus() {
|
||||
return networkPasswordStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the network password.
|
||||
*/
|
||||
private void validateNetworkPassword() {
|
||||
String string = networkPassword.getValue();
|
||||
if (string == null || string.length() == 0) {
|
||||
networkPasswordStatus.setValue(new FormStatus(R.string.setup_error_wlan_password_none));
|
||||
} else if (string.length() < 8) {
|
||||
networkPasswordStatus.setValue(new FormStatus(R.string.setup_error_wlan_password_too_short));
|
||||
} else {
|
||||
networkPasswordStatus.setValue(FormStatus.VALID);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the live data with the device name.
|
||||
*
|
||||
* @return The live data with the device name.
|
||||
*/
|
||||
public MutableLiveData<String> getDeviceName() {
|
||||
return deviceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the status for the device name.
|
||||
*
|
||||
* @return The live data with the status for the device name.
|
||||
*/
|
||||
public LiveData<FormStatus> getDeviceNameStatus() {
|
||||
return deviceNameStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the device name.
|
||||
*/
|
||||
private void validateDeviceName() {
|
||||
String string = deviceName.getValue();
|
||||
if (string == null || string.length() == 0) {
|
||||
deviceNameStatus.setValue(new FormStatus(R.string.setup_error_device_name_too_short));
|
||||
} else {
|
||||
deviceNameStatus.setValue(FormStatus.VALID);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the longitude.
|
||||
*
|
||||
* @return The live data with the longitude.
|
||||
*/
|
||||
public MutableLiveData<String> getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the longitude status.
|
||||
*
|
||||
* @return The live data with the longitude status.
|
||||
*/
|
||||
public LiveData<FormStatus> getLongitudeStatus() {
|
||||
return longitudeStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the manual longitude input.
|
||||
*/
|
||||
private void validateLongitude() {
|
||||
Double lng = null;
|
||||
try {
|
||||
String string = longitude.getValue();
|
||||
if (string != null) {
|
||||
lng = parseValue(string);
|
||||
if (lng < -180 || lng > 180) {
|
||||
lng = null;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) { }
|
||||
if (lng != null) {
|
||||
longitudeStatus.setValue(FormStatus.VALID);
|
||||
} else if (!manualPosition.getValue()) {
|
||||
longitudeStatus.setValue(null);
|
||||
} else {
|
||||
longitudeStatus.setValue(new FormStatus(R.string.setup_error_longitude));
|
||||
}
|
||||
}
|
||||
|
||||
private String toString(double value) {
|
||||
LocaleListCompat c = ConfigurationCompat.getLocales(getApplication().getResources().getConfiguration());
|
||||
if (c.size() > 0) {
|
||||
Locale locale = c.get(0);
|
||||
DecimalFormat f = new DecimalFormat("0.000000", new DecimalFormatSymbols(locale));
|
||||
return f.format(value);
|
||||
}
|
||||
return "" + value;
|
||||
}
|
||||
|
||||
private Double parseValue(String value) {
|
||||
if (value == null) return null;
|
||||
value = value.trim();
|
||||
LocaleListCompat c = ConfigurationCompat.getLocales(getApplication().getResources().getConfiguration());
|
||||
for (int i = 0; i < c.size(); i++) {
|
||||
Locale l = c.get(i);
|
||||
NumberFormat f = NumberFormat.getNumberInstance(l);
|
||||
try {
|
||||
return ((Number)f.parseObject(value)).doubleValue();
|
||||
} catch (ParseException e) {
|
||||
Log.d(TAG, "Failed to parse double from: " + value);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(value.replace(',', '.'));
|
||||
} catch (NumberFormatException e) {
|
||||
Log.d(TAG, "Failed to parse double, giving up: " + value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the latitude.
|
||||
*
|
||||
* @return The live data with the latitude.
|
||||
*/
|
||||
public MutableLiveData<String> getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the latitude status.
|
||||
*
|
||||
* @return The live data with the latitude status.
|
||||
*/
|
||||
|
||||
public LiveData<FormStatus> getLatitudeStatus() {
|
||||
return latitudeStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a manually entered latitude.
|
||||
*/
|
||||
public void validateLatitude() {
|
||||
Double lat = null;
|
||||
try {
|
||||
String string = latitude.getValue();
|
||||
if (string != null) {
|
||||
lat = parseValue(string);
|
||||
if (lat < -90 || lat > 90) {
|
||||
lat = null;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) { }
|
||||
if (lat != null) {
|
||||
latitudeStatus.setValue(FormStatus.VALID);
|
||||
} else if (!manualPosition.getValue()) {
|
||||
latitudeStatus.setValue(null);
|
||||
} else {
|
||||
latitudeStatus.setValue(new FormStatus(R.string.setup_error_latitude));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the gps state.
|
||||
*
|
||||
* @return The live data with the gps state.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getGpsRegistered() {
|
||||
return gpsRegistered;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live data with the switch state.
|
||||
*
|
||||
* @return The live data with the switch state.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getManualPosition() {
|
||||
return manualPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the enabled state of the gps button.
|
||||
*
|
||||
* @return The enabled state of the gps button.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getGpsEnabled() {
|
||||
return gpsEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the live data with the final validity
|
||||
* state of the form.
|
||||
*
|
||||
* @return The live data with the form validity.
|
||||
*/
|
||||
public MutableLiveData<Boolean> getValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the status of the animation flag.
|
||||
*
|
||||
* @return True to animate.
|
||||
*/
|
||||
public boolean isAnimate() {
|
||||
return animate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the animation flag.
|
||||
*
|
||||
* @param animate The animation flag.
|
||||
*/
|
||||
public void setAnimate(boolean animate) {
|
||||
this.animate = animate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the summary of all validation states.
|
||||
*/
|
||||
private void validate() {
|
||||
getValid().setValue(
|
||||
getLongitudeStatus().getValue() != null && ! getLongitudeStatus().getValue().isError() &&
|
||||
getLatitudeStatus().getValue() != null && ! getLatitudeStatus().getValue().isError() &&
|
||||
getDeviceNameStatus().getValue() != null && !getDeviceNameStatus().getValue().isError() &&
|
||||
getNetworkNameStatus().getValue() != null && !getNetworkNameStatus().getValue().isError() &&
|
||||
getNetworkPasswordStatus().getValue() != null && !getNetworkPasswordStatus().getValue().isError()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the gps receiver (if not running already) and returns the
|
||||
* status.
|
||||
*
|
||||
* @return The status of the registration.
|
||||
*/
|
||||
public GpsStatus registerGpsReceiver() {
|
||||
if (gpsRegistered.getValue()) {
|
||||
return GpsStatus.SUCCESS;
|
||||
} else {
|
||||
if (PermissionUtil.hasForegroundPermissions(getApplication())) {
|
||||
LocationManager manager = (LocationManager)getApplication().getSystemService(Context.LOCATION_SERVICE);
|
||||
if (manager != null && manager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
try {
|
||||
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
|
||||
gpsRegistered.setValue(true);
|
||||
return GpsStatus.SUCCESS;
|
||||
} catch (SecurityException e) {
|
||||
return GpsStatus.PROHIBITED;
|
||||
}
|
||||
} else {
|
||||
return GpsStatus.DISABLED;
|
||||
}
|
||||
} else {
|
||||
return GpsStatus.PROHIBITED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters the gps receiver.
|
||||
*/
|
||||
public void unregisterGpsReciever() {
|
||||
if (gpsRegistered.getValue()) {
|
||||
// cleanup the gps receiver
|
||||
LocationManager manager = (LocationManager)getApplication().getSystemService(Context.LOCATION_SERVICE);
|
||||
if (manager != null) {
|
||||
manager.removeUpdates(locationListener);
|
||||
gpsRegistered.setValue(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the arguments to connect with.
|
||||
*
|
||||
* @return The arguments.
|
||||
*/
|
||||
public @Nullable ConnectFragment.Args getArgs() {
|
||||
Double latitude = parseValue(getLatitude().getValue());
|
||||
if (latitude == null) return null;
|
||||
Double longitude = parseValue(getLongitude().getValue());
|
||||
if (longitude == null) return null;
|
||||
return new ConnectFragment.Args(getDeviceName().getValue(),
|
||||
getNetworkName().getValue(), getNetworkPassword().getValue(),
|
||||
longitude, latitude);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
unregisterGpsReciever();
|
||||
super.onCleared();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.DataSource;
|
||||
@@ -13,17 +12,13 @@ import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.database.Favorite;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.app.task.DatabaseTask;
|
||||
import com.mowesta.android.app.task.TaskStatus;
|
||||
import com.mowesta.android.feign.api.DefaultApi;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.CityPage;
|
||||
import com.mowesta.android.feign.model.Country;
|
||||
import com.mowesta.android.feign.model.LocationReference;
|
||||
import com.mowesta.android.feign.model.State;
|
||||
|
||||
@@ -60,7 +55,7 @@ public class StateViewModel extends AbstractPlaceViewModel {
|
||||
/**
|
||||
* A handler to run on main.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* The loader for the state.
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.DataSource;
|
||||
@@ -14,8 +13,7 @@ import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.binding.DiagramEntry;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.WeatherReport;
|
||||
import com.mowesta.android.feign.model.WeatherReportPage;
|
||||
@@ -23,7 +21,6 @@ import com.mowesta.android.feign.model.WeatherStation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* The view model to show a page with the weather station and
|
||||
@@ -65,7 +62,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* The handler to run on main.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates a new view model.
|
||||
@@ -204,7 +201,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<WeatherReport>> callback) {
|
||||
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
|
||||
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(now, id, 0l, params.requestedStartPosition, params.requestedLoadSize ); },
|
||||
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
|
||||
(id, status) -> { finishRequest(requestCode, true); });
|
||||
if (id != null && isCurrentRequest(requestCode)) {
|
||||
@@ -215,7 +212,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<DiagramEntry<WeatherReport>> callback) {
|
||||
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0l, now, params.startPosition, params.loadSize ); },
|
||||
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(now, id, 0l, params.startPosition, params.loadSize ); },
|
||||
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()))); },
|
||||
(id, status) -> { finishRequest(requestCode, true); });
|
||||
if (id != null && isCurrentRequest(requestCode)) {
|
||||
|
||||
@@ -1,33 +1,17 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Handler;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.paging.DataSource;
|
||||
import androidx.paging.LivePagedListBuilder;
|
||||
import androidx.paging.PagedList;
|
||||
import androidx.paging.PagedListAdapter;
|
||||
import androidx.paging.PositionalDataSource;
|
||||
import androidx.recyclerview.widget.DiffUtil;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.mowesta.android.app.IApp;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.ViewStationEntryBinding;
|
||||
import com.mowesta.android.app.repository.ClientFactory;
|
||||
import com.mowesta.android.app.task.ApiTask;
|
||||
import com.mowesta.android.feign.model.City;
|
||||
import com.mowesta.android.feign.model.CityPage;
|
||||
import com.mowesta.android.feign.model.WeatherStation;
|
||||
import com.mowesta.android.feign.model.WeatherStationPage;
|
||||
|
||||
@@ -64,7 +48,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
|
||||
/**
|
||||
* The handler to debounce the updates to the search term.
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
private Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* Creates the view model.
|
||||
@@ -166,7 +150,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<WeatherStation> callback) {
|
||||
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term,0, params.requestedLoadSize ); },
|
||||
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(0, params.requestedLoadSize, term); },
|
||||
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements(), 0, page.getTotal())); },
|
||||
(v, status) -> { finishRequest(requestCode, true); });
|
||||
if (isCurrentRequest(requestCode)) {
|
||||
@@ -177,7 +161,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
|
||||
|
||||
@Override
|
||||
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<WeatherStation> callback) {
|
||||
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term, params.startPosition, params.loadSize); },
|
||||
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(params.startPosition, params.loadSize, term); },
|
||||
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements())); },
|
||||
(v, status) -> { finishRequest(requestCode, true);});
|
||||
if (isCurrentRequest(requestCode)) {
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.mowesta.android.app.model;
|
||||
import android.app.Application;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user