├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradlew
├── gradlew.bat
├── novel
├── .gitignore
├── build.gradle
├── proguard-rules.txt
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── ic_launcher-web.png
│ ├── java
│ └── com
│ │ └── chhuang
│ │ └── novel
│ │ ├── AppContext.java
│ │ ├── ArticleActivity.java
│ │ ├── DirectoryActivity.java
│ │ └── data
│ │ ├── Article.java
│ │ ├── GBKRequest.java
│ │ ├── articles
│ │ ├── BenghuaiNovel.java
│ │ ├── INovel.java
│ │ └── LingaoqimingNovel.java
│ │ ├── dao
│ │ ├── ArticleDataHelper.java
│ │ ├── ArticleInfo.java
│ │ ├── BaseModelHelper.java
│ │ ├── ContentKey.java
│ │ ├── DataContentProvider.java
│ │ └── DatabaseHelper.java
│ │ └── sql
│ │ ├── Column.java
│ │ └── SQLiteTable.java
│ └── res
│ ├── drawable-hdpi
│ └── ic_launcher.png
│ ├── drawable-mdpi
│ └── ic_launcher.png
│ ├── drawable-xhdpi
│ └── ic_launcher.png
│ ├── drawable-xxhdpi
│ └── ic_launcher.png
│ ├── layout
│ ├── activity_article.xml
│ ├── activity_directory.xml
│ ├── drawer_sidebar.xml
│ └── title_item.xml
│ ├── menu
│ └── article.xml
│ ├── values-v11
│ └── styles.xml
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── attrs.xml
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 | *.sln merge=union
7 | *.csproj merge=union
8 | *.vbproj merge=union
9 | *.fsproj merge=union
10 | *.dbproj merge=union
11 |
12 | # Standard to msysgit
13 | *.doc diff=astextplain
14 | *.DOC diff=astextplain
15 | *.docx diff=astextplain
16 | *.DOCX diff=astextplain
17 | *.dot diff=astextplain
18 | *.DOT diff=astextplain
19 | *.pdf diff=astextplain
20 | *.PDF diff=astextplain
21 | *.rtf diff=astextplain
22 | *.RTF diff=astextplain
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .gradle
3 | /local.properties
4 | /.idea/
5 | .DS_Store
6 | /.idea/libraries/
7 | *.iml
8 | /build
9 | =======
10 | # Built application files
11 | *.apk
12 | *.ap_
13 |
14 | # Files for the Dalvik VM
15 | *.dex
16 |
17 | # Java class files
18 | *.class
19 |
20 | # Generated files
21 | bin/
22 | gen/
23 |
24 | # Gradle files
25 | .gradle/
26 | build/
27 |
28 | # Local configuration file (sdk path, etc)
29 | local.properties
30 |
31 | # Proguard folder generated by Eclipse
32 | proguard/
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | novel
2 | =====
3 |
4 | 小说阅读器
5 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:0.12.+'
9 | }
10 | }
11 |
12 | allprojects {
13 | repositories {
14 | mavenCentral()
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Settings specified in this file will override any Gradle settings
5 | # configured through the IDE.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/novel/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/novel/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android'
2 |
3 | android {
4 | compileSdkVersion 19
5 | buildToolsVersion "19.1.0"
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 19
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 |
14 | buildTypes {
15 | release {
16 | runProguard false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
18 | }
19 | }
20 |
21 | sourceSets {
22 | test {
23 | java.srcDir file('src.test')
24 | }
25 | }
26 | }
27 |
28 | dependencies {
29 | compile 'org.roboguice:roboguice:2.+'
30 | compile 'com.android.support:support-v4:19+'
31 | compile 'com.mcxiaoke.volley:library:1.0.+'
32 | compile 'org.jsoup:jsoup:1.+'
33 | compile 'com.google.code.gson:gson:2.2.4'
34 | compile 'joda-time:joda-time:1.6.+'
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | testCompile 'junit:junit:4+'
37 | testCompile 'org.robolectric:robolectric:2+'
38 | }
39 |
--------------------------------------------------------------------------------
/novel/proguard-rules.txt:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:/Users/chhuang/AppData/Local/Android/android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the ProGuard
5 | # include property in project.properties.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
--------------------------------------------------------------------------------
/novel/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
14 |
18 |
19 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/novel/src/main/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangcd/novel/8409e97819a7936c1c6d83003a86b25fdb91a069/novel/src/main/ic_launcher-web.png
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/AppContext.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.widget.Toast;
6 | import com.android.volley.RequestQueue;
7 | import com.android.volley.toolbox.Volley;
8 | import com.chhuang.novel.data.articles.BenghuaiNovel;
9 | import com.chhuang.novel.data.articles.INovel;
10 | import com.chhuang.novel.data.articles.LingaoqimingNovel;
11 |
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 | /**
16 | * Date: 2014/6/2
17 | * Time: 14:38
18 | *
19 | * @author chhuang@microsoft.com
20 | */
21 | public class AppContext extends Application {
22 | public static final List registerNovels = new ArrayList() {
23 | {
24 | add(new BenghuaiNovel());
25 | add(new LingaoqimingNovel());
26 | }
27 | };
28 | private static AppContext context;
29 | private RequestQueue queue;
30 |
31 | public static void showToast(final Activity activity, final String content, final int length) {
32 | activity.runOnUiThread(new Runnable() {
33 | @Override
34 | public void run() {
35 | Toast.makeText(activity, content, length).show();
36 | }
37 | });
38 | }
39 |
40 | public static AppContext getContext() {
41 | return context;
42 | }
43 |
44 | @Override
45 | public void onCreate() {
46 | super.onCreate();
47 | context = (AppContext) getApplicationContext();
48 | queue = Volley.newRequestQueue(this);
49 | }
50 |
51 | public RequestQueue getQueue() {
52 | return queue;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/ArticleActivity.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.os.Bundle;
6 | import android.support.v4.widget.SwipeRefreshLayout;
7 | import android.text.TextUtils;
8 | import android.util.Log;
9 | import android.view.Window;
10 | import android.widget.ScrollView;
11 | import android.widget.TextView;
12 | import android.widget.Toast;
13 | import com.android.volley.Response;
14 | import com.android.volley.VolleyError;
15 | import com.chhuang.novel.data.Article;
16 | import com.chhuang.novel.data.articles.INovel;
17 | import com.chhuang.novel.data.dao.ArticleDataHelper;
18 | import roboguice.activity.RoboActivity;
19 | import roboguice.inject.ContentView;
20 | import roboguice.inject.InjectView;
21 |
22 | @ContentView(R.layout.activity_article)
23 | public class ArticleActivity extends RoboActivity implements SwipeRefreshLayout.OnRefreshListener {
24 | public static final String TAG = ArticleActivity.class.getName();
25 | @InjectView(R.id.layout_article)
26 | SwipeRefreshLayout layoutArticle;
27 | @InjectView(R.id.content)
28 | TextView contentView;
29 | @InjectView(R.id.sroll_view_content)
30 | ScrollView scrollView;
31 | private Article article;
32 | private INovel novel;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | requestWindowFeature(Window.FEATURE_NO_TITLE);
37 | super.onCreate(savedInstanceState);
38 |
39 | init();
40 | }
41 |
42 | private void init() {
43 | layoutArticle.setColorScheme(android.R.color.holo_blue_bright,
44 | android.R.color.holo_green_light,
45 | android.R.color.holo_orange_light,
46 | android.R.color.holo_red_light);
47 | layoutArticle.setOnRefreshListener(this);
48 | Intent intent = getIntent();
49 | article = intent.getParcelableExtra("article");
50 | try {
51 | novel = (INovel) Class.forName(intent.getStringExtra("novel")).newInstance();
52 | } catch (Exception e) {
53 | Log.w(TAG, "Failed to create INovel instance", e);
54 | finish();
55 | }
56 |
57 | if (TextUtils.isEmpty(article.getContent())) {
58 | onRefresh();
59 | } else {
60 | setText();
61 | }
62 | }
63 |
64 | private void setText() {
65 | contentView.setText(article.getContent());
66 | scrollView.post(new Runnable() {
67 | @Override
68 | public void run() {
69 | final int y = (int) (article.getPercentage() * contentView.getHeight() - scrollView.getHeight());
70 | scrollView.scrollTo(0, y);
71 | }
72 | });
73 | }
74 |
75 | @Override
76 | public void onRefresh() {
77 | layoutArticle.setRefreshing(true);
78 | final AppContext context = AppContext.getContext();
79 | context.getQueue().add(novel.getFactory().create(article.getUrl(), new Response.Listener() {
80 | @Override
81 | public void onResponse(String response) {
82 | String content = novel.parseArticle(response);
83 | contentView.setText(content);
84 | layoutArticle.setRefreshing(false);
85 | article.setContent(content);
86 | Uri uri = ArticleDataHelper.getInstance(context).insert(article);
87 | Log.v(TAG, "Article uri: " + uri);
88 | }
89 | }, new Response.ErrorListener() {
90 | @Override
91 | public void onErrorResponse(VolleyError error) {
92 | AppContext.showToast(ArticleActivity.this, "刷新失败,请稍后重试", Toast.LENGTH_LONG);
93 | layoutArticle.setRefreshing(false);
94 | }
95 | }));
96 | }
97 |
98 | @Override
99 | public void onBackPressed() {
100 | final double percentage = (scrollView.getScrollY() + scrollView.getHeight()) * 1.0 / contentView.getHeight();
101 | article.setPercentage(percentage);
102 | ArticleDataHelper.getInstance(AppContext.getContext()).insert(article);
103 | super.onBackPressed();
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/DirectoryActivity.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel;
2 |
3 | import android.app.LoaderManager;
4 | import android.content.Context;
5 | import android.content.CursorLoader;
6 | import android.content.Intent;
7 | import android.content.Loader;
8 | import android.database.Cursor;
9 | import android.net.Uri;
10 | import android.os.Bundle;
11 | import android.support.v4.app.ActionBarDrawerToggle;
12 | import android.support.v4.widget.DrawerLayout;
13 | import android.support.v4.widget.SwipeRefreshLayout;
14 | import android.text.TextUtils;
15 | import android.util.Log;
16 | import android.view.*;
17 | import android.widget.*;
18 | import com.android.volley.Response;
19 | import com.android.volley.VolleyError;
20 | import com.chhuang.novel.data.Article;
21 | import com.chhuang.novel.data.articles.INovel;
22 | import com.chhuang.novel.data.dao.ArticleDataHelper;
23 | import com.chhuang.novel.data.dao.ArticleInfo;
24 | import roboguice.activity.RoboActivity;
25 | import roboguice.inject.ContentView;
26 | import roboguice.inject.InjectView;
27 |
28 | import java.util.ArrayList;
29 | import java.util.Collections;
30 | import java.util.List;
31 | import java.util.concurrent.atomic.AtomicInteger;
32 |
33 |
34 | @ContentView(R.layout.activity_directory)
35 | public class DirectoryActivity extends RoboActivity
36 | implements SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks {
37 | public static final String TAG = DirectoryActivity.class.getName();
38 | @InjectView(R.id.layout_drawer)
39 | DrawerLayout drawerLayout;
40 | @InjectView(R.id.layout_titles)
41 | SwipeRefreshLayout layoutTitles;
42 | @InjectView(R.id.list_titles)
43 | ListView listViewTitles;
44 | @InjectView(R.id.drawer_sidebar)
45 | RelativeLayout drawerSidebar;
46 | @InjectView(R.id.sidebar_list_view)
47 | ListView listViewSidebar;
48 | private SimpleCursorAdapter articleAdapter;
49 | private INovel novel;
50 | private int lastVisitPosition;
51 |
52 | @Override
53 | protected void onCreate(Bundle savedInstanceState) {
54 | requestWindowFeature(Window.FEATURE_NO_TITLE);
55 | super.onCreate(savedInstanceState);
56 |
57 | init();
58 | }
59 |
60 | private void init() {
61 | ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
62 | this, /* host Activity */
63 | drawerLayout, /* DrawerLayout object */
64 | R.drawable.ic_launcher, /* nav drawer image to replace 'Up' caret */
65 | R.string.drawer_open, /* "open drawer" description for accessibility */
66 | R.string.drawer_close /* "close drawer" description for accessibility */
67 | ) {
68 | public void onDrawerClosed(View view) {
69 | invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
70 | }
71 |
72 | public void onDrawerOpened(View drawerView) {
73 | invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
74 | }
75 |
76 | @Override
77 | public void onDrawerSlide(View drawerView, float slideOffset) {
78 | float moveFactor = (drawerSidebar.getWidth() * slideOffset);
79 | layoutTitles.setTranslationX(moveFactor);
80 | }
81 | };
82 |
83 | drawerLayout.setDrawerListener(drawerToggle);
84 | listViewSidebar.setAdapter(new ArrayAdapter(this,
85 | android.R.layout.simple_list_item_1,
86 | AppContext.registerNovels));
87 | listViewSidebar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
88 | @Override
89 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
90 | final INovel newNovel = (INovel) listViewSidebar.getAdapter().getItem(position);
91 | drawerLayout.closeDrawer(drawerSidebar);
92 | if (novel.equals(newNovel)) {
93 | return;
94 | }
95 | getSharedPreferences(TAG, MODE_PRIVATE)
96 | .edit()
97 | .putInt(novel.getBookName() + "#list_selection", lastVisitPosition)
98 | .commit();
99 | novel = newNovel;
100 | Log.i(TAG, "Switch novel to " + novel);
101 | getLoaderManager().restartLoader(novel.hashCode(), null, DirectoryActivity.this);
102 | }
103 | });
104 |
105 | novel = AppContext.registerNovels.get(0);
106 | getLoaderManager().restartLoader(novel.hashCode(), null, this);
107 |
108 | layoutTitles.setOnRefreshListener(this);
109 | layoutTitles.setColorScheme(android.R.color.holo_blue_bright,
110 | android.R.color.holo_green_light,
111 | android.R.color.holo_orange_light,
112 | android.R.color.holo_red_light);
113 | articleAdapter = new ArticleCursorAdapter(this,
114 | R.layout.title_item,
115 | null,
116 | new String[0],
117 | new int[0],
118 | 0);
119 | listViewTitles.setAdapter(articleAdapter);
120 | listViewTitles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
121 | @Override
122 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
123 | Cursor cursor = ((SimpleCursorAdapter) listViewTitles.getAdapter()).getCursor();
124 | if (cursor == null) {
125 | return;
126 | }
127 | cursor.moveToPosition(position);
128 | lastVisitPosition = position;
129 | Article article = ArticleDataHelper.fromCursor(cursor);
130 | Intent intent = new Intent(DirectoryActivity.this, ArticleActivity.class)
131 | .putExtra("article", article)
132 | .putExtra("novel", novel.getClass().getCanonicalName());
133 | startActivity(intent);
134 | }
135 | });
136 | registerForContextMenu(listViewTitles);
137 | }
138 |
139 | @Override
140 | protected void onPause() {
141 | getSharedPreferences(TAG, MODE_PRIVATE)
142 | .edit()
143 | .putInt(novel.getBookName() + "#list_selection", lastVisitPosition)
144 | .commit();
145 | super.onPause();
146 | }
147 |
148 | @Override
149 | public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
150 | if (v.getId() == R.id.list_titles) {
151 | menu.setHeaderTitle("下载");
152 | menu.add(Menu.NONE, 0, 0, "下载本章");
153 | menu.add(Menu.NONE, 1, 1, "下载之后所有章节");
154 | }
155 | }
156 |
157 | @Override
158 | public boolean onContextItemSelected(MenuItem item) {
159 | ContextMenu.ContextMenuInfo contextMenuInfo = item.getMenuInfo();
160 | if (contextMenuInfo instanceof AdapterView.AdapterContextMenuInfo) {
161 | AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) contextMenuInfo;
162 | Cursor cursor = ((SimpleCursorAdapter) listViewTitles.getAdapter()).getCursor();
163 | cursor.moveToPosition(info.position);
164 | switch (item.getItemId()) {
165 | case 0:
166 | singleDownload(cursor);
167 | break;
168 | case 1:
169 | do {
170 | singleDownload(cursor);
171 | } while (cursor.moveToNext());
172 | }
173 | return true;
174 | }
175 | return super.onContextItemSelected(item);
176 | }
177 |
178 | private void singleDownload(Cursor cursor) {
179 | final Article article = ArticleDataHelper.fromCursor(cursor);
180 | final Response.Listener responseListener = new Response.Listener() {
181 | @Override
182 | public void onResponse(String response) {
183 | String content = novel.parseArticle(response);
184 | article.setContent(content);
185 | Uri uri = ArticleDataHelper.getInstance(
186 | AppContext.getContext()).insert(article);
187 | Log.v(TAG, "Article uri: " + uri);
188 | }
189 | };
190 | final Response.ErrorListener errorListener = new Response.ErrorListener() {
191 | @Override
192 | public void onErrorResponse(VolleyError error) {
193 | AppContext.showToast(DirectoryActivity.this, article.getTitle() + " 下载失败,请稍后重试", Toast.LENGTH_LONG);
194 | }
195 | };
196 | AppContext.getContext().getQueue().add(
197 | novel.getFactory().create(article.getUrl(), responseListener, errorListener));
198 | }
199 |
200 | // TODO bulkInsert for articles
201 | private void multipleDownload(Cursor cursor) {
202 | final List synchronizedArticleList = Collections.synchronizedList(new ArrayList());
203 | AtomicInteger taskCount = new AtomicInteger(0);
204 | final AtomicInteger finishCount = new AtomicInteger(0);
205 | do {
206 | final Article article = ArticleDataHelper.fromCursor(cursor);
207 | taskCount.getAndIncrement();
208 | final Response.Listener responseListener = new Response.Listener() {
209 | @Override
210 | public void onResponse(String response) {
211 | String content = novel.parseArticle(response);
212 | article.setContent(content);
213 | synchronizedArticleList.add(article);
214 | finishCount.getAndIncrement();
215 | }
216 | };
217 | final Response.ErrorListener errorListener = new Response.ErrorListener() {
218 | @Override
219 | public void onErrorResponse(VolleyError error) {
220 | AppContext.showToast(DirectoryActivity.this, article.getTitle() + " 下载失败,请稍后重试", Toast.LENGTH_LONG);
221 | finishCount.getAndIncrement();
222 | }
223 | };
224 | AppContext.getContext().getQueue().add(
225 | novel.getFactory().create(article.getUrl(), responseListener, errorListener));
226 | }
227 | while (cursor.moveToNext());
228 | // finishCount.compareAndSet()
229 | }
230 |
231 | @Override
232 | public Loader onCreateLoader(int id, Bundle args) {
233 | for (INovel novel : AppContext.registerNovels) {
234 | if (novel.hashCode() == id) {
235 | return new CursorLoader(this,
236 | ArticleDataHelper.ARTICLE_CONTENT_URI,
237 | ArticleInfo.PROJECTIONS,
238 | ArticleInfo.NOVEL_NAME + " = ?",
239 | new String[]{novel.getBookName()},
240 | ArticleInfo.ID);
241 | }
242 | }
243 | return null;
244 | }
245 |
246 | @Override
247 | public void onLoadFinished(Loader loader, Cursor data) {
248 | articleAdapter.changeCursor(data);
249 | if (data == null || data.getCount() == 0) {
250 | onRefresh();
251 | } else {
252 | final int lastVisitPosition = getSharedPreferences(TAG, MODE_PRIVATE)
253 | .getInt(novel.getBookName() + "#list_selection", 0);
254 | Log.v(TAG, "Last visit position is " + lastVisitPosition);
255 | listViewTitles.post(new Runnable() {
256 | @Override
257 | public void run() {
258 | listViewTitles.setSelection(lastVisitPosition);
259 | }
260 | });
261 | }
262 | }
263 |
264 | @Override
265 | public void onRefresh() {
266 | layoutTitles.setRefreshing(true);
267 |
268 | Response.Listener responseListener = new Response.Listener() {
269 | @Override
270 | public void onResponse(String response) {
271 | ArrayList articles = novel.parseHomePageToArticles(response);
272 | ArticleDataHelper.getInstance(AppContext.getContext()).bulkInsert(articles);
273 | layoutTitles.setRefreshing(false);
274 | }
275 | };
276 | Response.ErrorListener errorListener = new Response.ErrorListener() {
277 | @Override
278 | public void onErrorResponse(VolleyError error) {
279 | AppContext.showToast(DirectoryActivity.this, "刷新失败,请稍后重试", Toast.LENGTH_LONG);
280 | layoutTitles.setRefreshing(false);
281 | }
282 | };
283 | AppContext.getContext().getQueue().add(
284 | novel.getFactory().create(novel.getBaseUrl(), responseListener, errorListener));
285 | }
286 |
287 | @Override
288 | public void onLoaderReset(Loader loader) {
289 | articleAdapter.changeCursor(null);
290 | }
291 |
292 |
293 | private static class ViewHolder {
294 | private TextView chapterNumber;
295 | private TextView chapterTitle;
296 | private ImageView star;
297 | private ProgressBar progressBar;
298 | }
299 |
300 | private class ArticleCursorAdapter extends SimpleCursorAdapter {
301 | private ArticleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
302 | super(context, layout, c, from, to, flags);
303 | }
304 |
305 | @Override
306 | public void bindView(View view, Context context, Cursor cursor) {
307 | ViewHolder holder;
308 | if (view == null) {
309 | LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
310 | view = inflater.inflate(R.layout.title_item, null);
311 | holder = new ViewHolder();
312 | holder.chapterNumber = (TextView) view.findViewById(R.id.text_chapter);
313 | holder.chapterTitle = (TextView) view.findViewById(R.id.text_title);
314 | holder.star = (ImageView) view.findViewById(R.id.image_status);
315 | holder.progressBar = (ProgressBar) view.findViewById(R.id.progress_article);
316 | view.setTag(holder);
317 | Log.v(TAG, String.format("Init view holder (%s, %s, %s)",
318 | holder.chapterNumber,
319 | holder.chapterTitle,
320 | holder.star));
321 | } else {
322 | holder = (ViewHolder) view.getTag();
323 | }
324 | if (holder == null) {
325 | holder = new ViewHolder();
326 | holder.chapterNumber = (TextView) view.findViewById(R.id.text_chapter);
327 | holder.chapterTitle = (TextView) view.findViewById(R.id.text_title);
328 | holder.star = (ImageView) view.findViewById(R.id.image_status);
329 | holder.progressBar = (ProgressBar) view.findViewById(R.id.progress_article);
330 | Log.v(TAG, String.format("Init view holder (%s, %s, %s), backup",
331 | holder.chapterNumber,
332 | holder.chapterTitle,
333 | holder.star));
334 | view.setTag(holder);
335 | }
336 | Article article = ArticleDataHelper.fromCursor(cursor);
337 | if (TextUtils.isEmpty(article.getContent())) {
338 | holder.star.setImageState(new int[]{android.R.attr.state_pressed}, false);
339 | } else {
340 | holder.star.setImageState(new int[]{android.R.attr.state_checked, android.R.attr.state_pressed}, false);
341 | }
342 | final int progress = (int) (100 * article.getPercentage());
343 | holder.chapterNumber.setText(String.format("%04d", article.getId()));
344 | holder.chapterTitle.setText(article.getTitle());
345 | holder.progressBar.setVisibility(View.VISIBLE);
346 | holder.progressBar.setProgress(progress);
347 | }
348 | }
349 | }
350 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/Article.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 | import com.chhuang.novel.data.dao.ContentKey;
6 |
7 | import static com.chhuang.novel.data.dao.ArticleInfo.*;
8 |
9 | /**
10 | * Date: 2014/5/23
11 | * Time: 16:01
12 | *
13 | * @author chhuang@microsoft.com
14 | */
15 | @SuppressWarnings("UnusedDeclaration")
16 | public class Article implements Parcelable {
17 | public final static Creator CREATOR = new Creator() {
18 | @Override
19 | public Article createFromParcel(Parcel source) {
20 | ClassLoader stringClassLoader = String.class.getClassLoader();
21 | int chapterNumber = source.readInt();
22 | String title = (String) source.readValue(stringClassLoader);
23 | String url = (String) source.readValue(stringClassLoader);
24 | Article article = new Article(chapterNumber, title, url);
25 | article.setPercentage(source.readDouble());
26 | article.setContent((String) source.readValue(stringClassLoader));
27 | article.setDateTime(source.readLong());
28 | article.setBookName((String) source.readValue(stringClassLoader));
29 | return article;
30 | }
31 |
32 | @Override
33 | public Article[] newArray(int size) {
34 | return new Article[size];
35 | }
36 | };
37 | @ContentKey(key = NOVEL_NAME)
38 | private String bookName;
39 | @ContentKey(key = PERCENTAGE)
40 | private double percentage;
41 | @ContentKey(key = CONTENT)
42 | private String content;
43 | @ContentKey(key = ID)
44 | private int id;
45 | @ContentKey(key = TITLE)
46 | private String title;
47 | @ContentKey(key = URL)
48 | private String url;
49 | @ContentKey(key = TIME)
50 | private long dateTime;
51 |
52 | public Article() {
53 | }
54 |
55 | public Article(int id, String title, String url) {
56 | this.id = id;
57 | this.title = title;
58 | this.url = url;
59 | }
60 |
61 | public String getBookName() {
62 | return bookName;
63 | }
64 |
65 | public void setBookName(String bookName) {
66 | this.bookName = bookName;
67 | }
68 |
69 | @Override
70 | public void writeToParcel(Parcel dest, int flags) {
71 | dest.writeInt(id);
72 | dest.writeValue(title);
73 | dest.writeValue(url);
74 | dest.writeDouble(percentage);
75 | dest.writeValue(content);
76 | dest.writeLong(dateTime);
77 | dest.writeValue(bookName);
78 | }
79 |
80 |
81 | public double getPercentage() {
82 | return percentage;
83 | }
84 |
85 | public void setPercentage(double percentage) {
86 | this.percentage = percentage;
87 | }
88 |
89 | public String getContent() {
90 | return content;
91 | }
92 |
93 | public void setContent(String content) {
94 | this.content = content;
95 | }
96 |
97 | public String getUrl() {
98 | return url;
99 | }
100 |
101 | public int getId() {
102 | return id;
103 | }
104 |
105 | public String getTitle() {
106 | return title;
107 | }
108 |
109 | @Override
110 | public int describeContents() {
111 | return 0;
112 | }
113 |
114 | public long getDateTime() {
115 | return dateTime;
116 | }
117 |
118 | public void setDateTime(long dateTime) {
119 | this.dateTime = dateTime;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/GBKRequest.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.Response;
5 | import com.android.volley.toolbox.HttpHeaderParser;
6 | import com.android.volley.toolbox.StringRequest;
7 |
8 | import java.io.UnsupportedEncodingException;
9 |
10 | /**
11 | * Date: 2014/5/26
12 | * Time: 11:10
13 | *
14 | * @author chhuang@microsoft.com
15 | */
16 | public class GBKRequest extends StringRequest {
17 | public GBKRequest(
18 | String url,
19 | Response.Listener listener,
20 | Response.ErrorListener errorListener) {
21 | super(url, listener, errorListener);
22 | }
23 |
24 | @Override
25 | protected Response parseNetworkResponse(NetworkResponse response) {
26 | String parsed;
27 | try {
28 | parsed = new String(response.data, "GBK");
29 | } catch (UnsupportedEncodingException e) {
30 | parsed = new String(response.data);
31 | }
32 | return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/articles/BenghuaiNovel.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.articles;
2 |
3 | import com.android.volley.Request;
4 | import com.android.volley.Response;
5 | import com.chhuang.novel.data.Article;
6 | import com.chhuang.novel.data.GBKRequest;
7 | import com.google.inject.Singleton;
8 | import org.jsoup.Jsoup;
9 | import org.jsoup.nodes.Document;
10 | import org.jsoup.nodes.Element;
11 | import org.jsoup.nodes.TextNode;
12 | import org.jsoup.select.Elements;
13 |
14 | import java.util.ArrayList;
15 | import java.util.regex.Matcher;
16 | import java.util.regex.Pattern;
17 |
18 | /**
19 | * Date: 2014/6/5
20 | * Time: 22:26
21 | *
22 | * @author chhuang@microsoft.com
23 | */
24 | public class BenghuaiNovel implements INovel {
25 | public static final Pattern ARTICLE_HREF_PATTERN = Pattern.compile("/5_5133/(\\d+).html",
26 | Pattern.CASE_INSENSITIVE);
27 | private static final String BASE_URL = "http://www.biquge.com/5_5133/";
28 | private final static String TAG = BenghuaiNovel.class.getName();
29 | private final static INovelRequestFactory factory = new INovelRequestFactory() {
30 | @Override
31 | public Request create(
32 | String url, Response.Listener responseListener, Response.ErrorListener errorListener) {
33 | return new GBKRequest(url, responseListener, errorListener);
34 | }
35 | };
36 |
37 | @Override
38 | public String getBaseUrl() {
39 | return BASE_URL;
40 | }
41 |
42 | @Override
43 | public String toString() {
44 | return getBookName();
45 | }
46 |
47 | @Override
48 | public String getBookName() {
49 | return "崩坏世界的传奇大冒险";
50 | }
51 |
52 | @Override
53 | public INovelRequestFactory getFactory() {
54 | return factory;
55 | }
56 |
57 | @Override
58 | public ArrayList parseHomePageToArticles(String response) {
59 | ArrayList articles = new ArrayList();
60 | Document document = Jsoup.parse(response);
61 | Elements dds = document.select("dd").select("a");
62 | for (Element a : dds) {
63 | String href = a.attr("href");
64 | Matcher matcher = ARTICLE_HREF_PATTERN.matcher(href);
65 | if (matcher.matches()) {
66 | int id = Integer.parseInt(matcher.group(1));
67 | String title = a.text();
68 | String url = BASE_URL + id + ".html";
69 | Article article = new Article(id, title, url);
70 | article.setBookName(getBookName());
71 | articles.add(article);
72 | }
73 | }
74 | return articles;
75 | }
76 |
77 | @Override
78 | public String parseArticle(String response) {
79 | Document document = Jsoup.parse(response);
80 | Element content = document.select("div#content").first();
81 | StringBuilder buffer = new StringBuilder();
82 | for (TextNode p : content.textNodes()) {
83 | buffer.append(p.getWholeText()).append("\r\n");
84 | }
85 | return buffer.toString();
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/articles/INovel.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.articles;
2 |
3 | import com.android.volley.Request;
4 | import com.android.volley.Response;
5 | import com.chhuang.novel.data.Article;
6 |
7 | import java.util.ArrayList;
8 |
9 | /**
10 | * Date: 2014/6/5
11 | * Time: 22:25
12 | *
13 | * @author chhuang@microsoft.com
14 | */
15 | public interface INovel {
16 | ArrayList parseHomePageToArticles(String response);
17 |
18 | String parseArticle(String response);
19 |
20 | String getBaseUrl();
21 |
22 | String getBookName();
23 |
24 | INovelRequestFactory getFactory();
25 |
26 | public interface INovelRequestFactory {
27 | Request create(
28 | String url,
29 | Response.Listener responseListener,
30 | Response.ErrorListener errorListener);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/articles/LingaoqimingNovel.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.articles;
2 |
3 | import com.android.volley.Request;
4 | import com.android.volley.Response;
5 | import com.chhuang.novel.data.Article;
6 | import com.chhuang.novel.data.GBKRequest;
7 | import org.jsoup.Jsoup;
8 | import org.jsoup.nodes.Document;
9 | import org.jsoup.nodes.Element;
10 | import org.jsoup.select.Elements;
11 |
12 | import java.util.ArrayList;
13 | import java.util.regex.Matcher;
14 | import java.util.regex.Pattern;
15 |
16 | /**
17 | * Date: 2014/6/9
18 | * Time: 22:35
19 | *
20 | * @author chhuang@microsoft.com
21 | */
22 | public class LingaoqimingNovel implements INovel {
23 | public final static Pattern ARTICLE_HREF_PATTERN = Pattern.compile("article/(\\d+).html",
24 | Pattern.CASE_INSENSITIVE);
25 | public final static String BASE_URL = "http://www.lingaoqiming.com/";
26 | private final static String TAG = LingaoqimingNovel.class.getName();
27 | private final static INovelRequestFactory factory = new INovelRequestFactory() {
28 | @Override
29 | public Request create(
30 | String url, Response.Listener responseListener, Response.ErrorListener errorListener) {
31 | return new GBKRequest(url, responseListener, errorListener);
32 | }
33 | };
34 |
35 | @Override
36 | public ArrayList parseHomePageToArticles(String response) {
37 | ArrayList articles = new ArrayList();
38 | Document document = Jsoup.parse(response);
39 | Elements elements = document.getElementsByAttributeValueMatching("href", ARTICLE_HREF_PATTERN);
40 | for (Element element : elements) {
41 | String href = element.attr("href");
42 | Matcher matcher = ARTICLE_HREF_PATTERN.matcher(href);
43 | if (matcher.matches()) {
44 | int articleIndex = Integer.parseInt(matcher.group(1));
45 | String title = element.text();
46 | String url = BASE_URL + matcher.group();
47 | Article article = new Article(articleIndex, title, url);
48 | article.setBookName(getBookName());
49 | articles.add(article);
50 | }
51 | }
52 | return articles;
53 | }
54 |
55 | @Override
56 | public String parseArticle(String response) {
57 | Document document = Jsoup.parse(response);
58 | Elements ps = document.select("div.gray14").select("p");
59 | StringBuilder buffer = new StringBuilder();
60 | for (Element p : ps) {
61 | buffer.append(p.text()).append("\r\n");
62 | }
63 | return buffer.toString();
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return getBookName();
69 | }
70 |
71 | @Override
72 | public String getBaseUrl() {
73 | return BASE_URL;
74 | }
75 |
76 | @Override
77 | public String getBookName() {
78 | return "临高启明";
79 | }
80 |
81 | @Override
82 | public INovelRequestFactory getFactory() {
83 | return factory;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/ArticleDataHelper.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import android.content.ContentValues;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.net.Uri;
7 | import com.chhuang.novel.data.Article;
8 |
9 | import java.text.MessageFormat;
10 | import java.util.List;
11 |
12 | import static com.chhuang.novel.data.dao.ArticleInfo.*;
13 |
14 | /**
15 | * Date: 2014/5/28
16 | * Time: 18:32
17 | * @author chhuang@microsoft.com
18 | */
19 | public class ArticleDataHelper extends BaseModelHelper {
20 |
21 | public static final String ARTICLE_CONTENT_URL_STRING = MessageFormat.format("content://{0}/{1}",
22 | DataContentProvider.AUTHORITY,
23 | TABLE_NAME);
24 | public static final Uri ARTICLE_CONTENT_URI = Uri.parse(ARTICLE_CONTENT_URL_STRING);
25 |
26 | private static ArticleDataHelper instance;
27 |
28 | private ArticleDataHelper(Context context) {
29 | super(context);
30 | }
31 |
32 | public synchronized static ArticleDataHelper getInstance(Context context) {
33 | if (instance == null) {
34 | instance = new ArticleDataHelper(context.getApplicationContext());
35 | }
36 | return instance;
37 | }
38 |
39 | public static Article fromCursor(Cursor cursor) {
40 | int id = cursor.getInt(cursor.getColumnIndex(ID));
41 | String title = cursor.getString(cursor.getColumnIndex(TITLE));
42 | String url = cursor.getString(cursor.getColumnIndex(URL));
43 | final byte[] blob = cursor.getBlob(cursor.getColumnIndex(CONTENT));
44 | String content = blob == null ? null : new String(blob);
45 | double percentage = cursor.getDouble(cursor.getColumnIndex(PERCENTAGE));
46 | String bookName = cursor.getString(cursor.getColumnIndex(NOVEL_NAME));
47 | Article article = new Article(id, title, url);
48 | article.setContent(content);
49 | article.setPercentage(percentage);
50 | article.setBookName(bookName);
51 | return article;
52 | }
53 |
54 | @Override
55 | protected Uri getContentUri() {
56 | return ARTICLE_CONTENT_URI;
57 | }
58 |
59 | public void bulkInsert(List articles) {
60 | int size = articles.size();
61 | ContentValues[] contentValues = new ContentValues[size];
62 | for (int i = 0; i < size; i++) {
63 | contentValues[i] = getContentValue(articles.get(i));
64 | }
65 | bulkInsert(contentValues);
66 | }
67 |
68 | public Uri insert(Article article) {
69 | ContentValues values = getContentValue(article);
70 | return insert(values);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/ArticleInfo.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import android.provider.BaseColumns;
4 | import com.chhuang.novel.data.sql.SQLiteTable;
5 |
6 | import static com.chhuang.novel.data.sql.Column.DataType.*;
7 |
8 | /**
9 | * Date: 2014/6/4
10 | * Time: 15:29
11 | *
12 | * @author chhuang
13 | */
14 | public class ArticleInfo implements BaseColumns {
15 | public static final String TABLE_NAME = "articles";
16 | public static final String NOVEL_NAME = "novel_name";
17 | public static final String TITLE = "title";
18 | public static final String CONTENT = "content";
19 | public static final String PERCENTAGE = "percentage";
20 | public static final String URL = "url";
21 | public static final String ID = "id";
22 | public static final String TIME = "time";
23 | public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
24 | .addColumn(NOVEL_NAME, TEXT)
25 | .addColumn(ID, INTEGER)
26 | .addColumn(PERCENTAGE, REAL)
27 | .addColumn(TITLE, TEXT)
28 | .addColumn(CONTENT, BLOB)
29 | .addColumn(URL, TEXT)
30 | .addColumn(TIME, INTEGER)
31 | .addUniqueColumns(NOVEL_NAME, ID);
32 | public static final String[] PROJECTIONS = new String[]{
33 | _ID, NOVEL_NAME, ID, PERCENTAGE, TITLE, CONTENT, URL, TIME};
34 |
35 | ArticleInfo() {
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/BaseModelHelper.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import android.content.ContentValues;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.net.Uri;
7 | import android.support.v4.content.CursorLoader;
8 | import android.util.Log;
9 | import com.google.gson.Gson;
10 | import com.google.gson.GsonBuilder;
11 |
12 | import java.lang.reflect.Field;
13 | import java.util.ArrayList;
14 | import java.util.HashMap;
15 |
16 | /**
17 | * Date: 2014/5/28
18 | * Time: 15:39
19 | *
20 | * @author chhuang
21 | */
22 | public abstract class BaseModelHelper {
23 | public static final String TAG = BaseModelHelper.class.getName();
24 | public static final Gson GSON = new GsonBuilder().create();
25 | private static final HashMap, ArrayList> annotatedFieldMap
26 | = new HashMap, ArrayList>();
27 | private Context context;
28 |
29 | public BaseModelHelper(Context context) {
30 | this.context = context;
31 | }
32 |
33 | public static T fromContentValues(Cursor cursor, Class klass) {
34 | T t;
35 | try {
36 | t = klass.newInstance();
37 | } catch (Exception e) {
38 | Log.w(TAG, Log.getStackTraceString(e));
39 | return null;
40 | }
41 | ArrayList annotatedFields = getAnnotatedFields(klass);
42 | for (Field field : annotatedFields) {
43 | Class fieldClass = field.getType();
44 | String key = field.getAnnotation(ContentKey.class).key();
45 | try {
46 | if (fieldClass.equals(String.class)) {
47 | field.set(t, cursor.getString(cursor.getColumnIndex(key)));
48 | } else if (fieldClass.equals(Long.class)) {
49 | field.setLong(t, cursor.getLong(cursor.getColumnIndex(key)));
50 | } else if (fieldClass.equals(Short.class)) {
51 | field.setShort(t, cursor.getShort(cursor.getColumnIndex(key)));
52 | } else if (fieldClass.equals(Integer.class)) {
53 | field.setInt(t, cursor.getInt(cursor.getColumnIndex(key)));
54 | } else if (fieldClass.equals(Byte.class)) {
55 | field.setByte(t, (byte) cursor.getInt(cursor.getColumnIndex(key)));
56 | } else if (fieldClass.equals(Float.class)) {
57 | field.setFloat(t, cursor.getFloat(cursor.getColumnIndex(key)));
58 | } else if (fieldClass.equals(Double.class)) {
59 | field.setDouble(t, cursor.getDouble(cursor.getColumnIndex(key)));
60 | } else if (fieldClass.equals(byte[].class)) {
61 | field.set(t, cursor.getString(cursor.getColumnIndex(key)));
62 | } else {
63 | field.set(t, GSON.fromJson(cursor.getString(cursor.getColumnIndex(key)), fieldClass));
64 | }
65 | } catch (IllegalAccessException e) {
66 | Log.w(TAG, Log.getStackTraceString(e));
67 | }
68 | }
69 | return t;
70 | }
71 |
72 | protected static ArrayList getAnnotatedFields(Class> klass) {
73 | ArrayList fields;
74 | if (!annotatedFieldMap.containsKey(klass)) {
75 | fields = new ArrayList();
76 | for (Field field : klass.getDeclaredFields()) {
77 | if (field.isAnnotationPresent(ContentKey.class)) {
78 | field.setAccessible(true);
79 | fields.add(field);
80 | }
81 | }
82 | annotatedFieldMap.put(klass, fields);
83 | return fields;
84 | }
85 | return annotatedFieldMap.get(klass);
86 | }
87 |
88 | public Context getContext() {
89 | return context;
90 | }
91 |
92 | public ContentValues getContentValue(T t) {
93 | Class> klass = t.getClass();
94 | ArrayList annotatedFields = getAnnotatedFields(klass);
95 | ContentValues values = new ContentValues(annotatedFields.size());
96 | for (Field field : annotatedFields) {
97 | String key = field.getAnnotation(ContentKey.class).key();
98 | try {
99 | Object value = field.get(t);
100 | if (value == null) {
101 | continue;
102 | }
103 | if (value instanceof String) {
104 | values.put(key, (String) value);
105 | } else if (value instanceof Long) {
106 | values.put(key, (Long) value);
107 | } else if (value instanceof Integer) {
108 | values.put(key, (Integer) value);
109 | } else if (value instanceof Byte) {
110 | values.put(key, (Byte) value);
111 | } else if (value instanceof Short) {
112 | values.put(key, (Short) value);
113 | } else if (value instanceof Float) {
114 | values.put(key, (Float) value);
115 | } else if (value instanceof Double) {
116 | values.put(key, (Double) value);
117 | } else if (value instanceof byte[]) {
118 | values.put(key, (byte[]) value);
119 | } else {
120 | values.put(key, GSON.toJson(value));
121 | }
122 | } catch (IllegalAccessException e) {
123 | Log.e(TAG, Log.getStackTraceString(e));
124 | }
125 | }
126 | return values;
127 | }
128 |
129 | public void notifyChange() {
130 | context.getContentResolver().notifyChange(getContentUri(), null);
131 | }
132 |
133 | protected abstract Uri getContentUri();
134 |
135 | public final Cursor query(
136 | Uri uri, String[] projection, String selection,
137 | String[] selectionArgs, String sortOrder) {
138 | return context.getContentResolver().query(uri, projection, selection, selectionArgs,
139 | sortOrder);
140 | }
141 |
142 | public final Cursor query(
143 | String[] projection, String selection, String[] selectionArgs,
144 | String sortOrder) {
145 | return query(getContentUri(), projection, selection, selectionArgs, sortOrder);
146 | }
147 |
148 | public final Uri insert(ContentValues values) {
149 | return context.getContentResolver().insert(getContentUri(), values);
150 | }
151 |
152 | public final int bulkInsert(ContentValues[] values) {
153 | return context.getContentResolver().bulkInsert(getContentUri(), values);
154 | }
155 |
156 | public final int update(ContentValues values, String where, String[] whereArgs) {
157 | return context.getContentResolver().update(getContentUri(), values, where, whereArgs);
158 | }
159 |
160 | public final int delete(String selection, String[] selectionArgs) {
161 | return context.getContentResolver().delete(getContentUri(), selection, selectionArgs);
162 | }
163 |
164 | public CursorLoader getCursorLoader(Context context) {
165 | return getCursorLoader(context, null, null, null, null);
166 | }
167 |
168 | protected final CursorLoader getCursorLoader(
169 | Context context, String[] projection,
170 | String selection, String[] selectionArgs, String sortOrder) {
171 | return new CursorLoader(context, getContentUri(), projection, selection, selectionArgs,
172 | sortOrder);
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/ContentKey.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import java.lang.annotation.Retention;
4 | import java.lang.annotation.RetentionPolicy;
5 |
6 | /**
7 | * Date: 2014/6/2
8 | * Time: 15:16
9 | *
10 | * @author chhuang@microsoft.com
11 | */
12 | @Retention(RetentionPolicy.RUNTIME)
13 | public @interface ContentKey {
14 | String key();
15 | }
16 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/DataContentProvider.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import android.content.ContentProvider;
4 | import android.content.ContentUris;
5 | import android.content.ContentValues;
6 | import android.content.UriMatcher;
7 | import android.database.Cursor;
8 | import android.database.SQLException;
9 | import android.database.sqlite.SQLiteDatabase;
10 | import android.database.sqlite.SQLiteQueryBuilder;
11 | import android.net.Uri;
12 | import android.util.Log;
13 | import com.chhuang.novel.AppContext;
14 |
15 | import java.util.concurrent.locks.ReentrantLock;
16 | import java.util.logging.Logger;
17 |
18 | /**
19 | * Date: 2014/6/2
20 | * Time: 13:56
21 | *
22 | * @author chhuang@microsoft.com
23 | */
24 | public class DataContentProvider extends ContentProvider {
25 | public static final String AUTHORITY = "com.chhuang.novel.provider";
26 | public static final String ARTICLE_CONTENT_TYPE = "vnd.android.cursor.dir/" + AUTHORITY + ".article";
27 | public static final String ARTICLE_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/"
28 | + AUTHORITY
29 | + ".article";
30 | public static final int ARTICLES = 0;
31 | public static final int ARTICLE = 1;
32 | public static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
33 | protected final static ReentrantLock DBLock = new ReentrantLock();
34 | private final static String TAG = DataContentProvider.class.getName();
35 | public static DatabaseHelper DBHelper;
36 |
37 | static {
38 | URI_MATCHER.addURI(AUTHORITY, ArticleInfo.TABLE_NAME, ARTICLES);
39 | URI_MATCHER.addURI(AUTHORITY, ArticleInfo.TABLE_NAME + "/#", ARTICLE);
40 | }
41 |
42 | public boolean onCreate() {
43 | return true;
44 | }
45 |
46 | @Override
47 | public Cursor query(
48 | Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
49 | DBLock.lock();
50 | try {
51 | SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
52 | String table = matchTable(uri);
53 | builder.setTables(table);
54 |
55 | SQLiteDatabase db = getDBHelper().getReadableDatabase();
56 | Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
57 | cursor.setNotificationUri(getContext().getContentResolver(), uri);
58 | return cursor;
59 | } finally {
60 | DBLock.unlock();
61 | }
62 | }
63 |
64 | public synchronized static DatabaseHelper getDBHelper() {
65 | if (DBHelper == null) {
66 | DBHelper = new DatabaseHelper(AppContext.getContext());
67 | }
68 | return DBHelper;
69 | }
70 |
71 | private String matchTable(Uri uri) {
72 | Log.v(TAG, "match table " + uri);
73 | switch (URI_MATCHER.match(uri)) {
74 | case ARTICLES:
75 | case ARTICLE:
76 | return ArticleInfo.TABLE_NAME;
77 | default:
78 | throw new IllegalArgumentException("Unknown URI " + uri);
79 | }
80 | }
81 |
82 | @Override
83 | public String getType(Uri uri) {
84 | switch (URI_MATCHER.match(uri)) {
85 | case ARTICLES:
86 | return ARTICLE_CONTENT_TYPE;
87 | case ARTICLE:
88 | return ARTICLE_CONTENT_ITEM_TYPE;
89 | default:
90 | throw new IllegalArgumentException("Unknown URI " + uri);
91 | }
92 | }
93 |
94 | @Override
95 | public int bulkInsert(Uri uri, ContentValues[] values) {
96 | DBLock.lock();
97 | try {
98 | String table = matchTable(uri);
99 | int insert = 0;
100 | SQLiteDatabase db = getDBHelper().getWritableDatabase();
101 | db.beginTransaction();
102 | try {
103 | for (ContentValues value : values) {
104 | long result = db.insertWithOnConflict(table, null, value, SQLiteDatabase.CONFLICT_IGNORE);
105 | if (result == -1) {
106 | Log.w(TAG, "Failed to insert content value: " + value);
107 | } else {
108 | insert++;
109 | }
110 | }
111 | db.setTransactionSuccessful();
112 | getContext().getContentResolver().notifyChange(uri, null);
113 | } catch (Exception ex) {
114 | Log.e(TAG, Log.getStackTraceString(ex));
115 | } finally {
116 | db.endTransaction();
117 | }
118 | return insert;
119 | } finally {
120 | DBLock.unlock();
121 | }
122 | }
123 |
124 | @Override
125 | public Uri insert(Uri uri, ContentValues values) {
126 | DBLock.lock();
127 | try {
128 | String table = matchTable(uri);
129 | SQLiteDatabase db = getDBHelper().getWritableDatabase();
130 | long rowId = 0;
131 | db.beginTransaction();
132 | try {
133 | rowId = db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE);
134 | db.setTransactionSuccessful();
135 | } catch (Exception ex) {
136 | Log.e(TAG, Log.getStackTraceString(ex));
137 | } finally {
138 | db.endTransaction();
139 | }
140 | if (rowId > 0) {
141 | Uri returnUri = ContentUris.withAppendedId(uri, rowId);
142 | getContext().getContentResolver().notifyChange(uri, null);
143 | return returnUri;
144 | }
145 | throw new SQLException("Failed to insert row into " + uri);
146 | } finally {
147 | DBLock.unlock();
148 | }
149 | }
150 |
151 | @Override
152 | public int delete(Uri uri, String selection, String[] selectionArgs) {
153 | DBLock.lock();
154 | try {
155 | String table = matchTable(uri);
156 | SQLiteDatabase db = getDBHelper().getWritableDatabase();
157 | int count = 0;
158 | db.beginTransaction();
159 | try {
160 | count = db.delete(table, selection, selectionArgs);
161 | db.setTransactionSuccessful();
162 | } catch (Exception ex) {
163 | Log.e(TAG, Log.getStackTraceString(ex));
164 | } finally {
165 | db.endTransaction();
166 | }
167 | getContext().getContentResolver().notifyChange(uri, null);
168 | return count;
169 | } finally {
170 | DBLock.unlock();
171 | }
172 | }
173 |
174 | @Override
175 | public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
176 | DBLock.lock();
177 | try {
178 | String table = matchTable(uri);
179 | SQLiteDatabase db = getDBHelper().getWritableDatabase();
180 | int count = 0;
181 | db.beginTransaction();
182 | try {
183 | count = db.update(table, values, selection, selectionArgs);
184 | db.setTransactionSuccessful();
185 | } catch (Exception ex) {
186 | Log.e(TAG, Log.getStackTraceString(ex));
187 | } finally {
188 | db.endTransaction();
189 | }
190 | getContext().getContentResolver().notifyChange(uri, null);
191 | return count;
192 | } finally {
193 | DBLock.unlock();
194 | }
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/dao/DatabaseHelper.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.dao;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.database.sqlite.SQLiteOpenHelper;
6 |
7 | /**
8 | * Date: 2014/5/27
9 | * Time: 13:24
10 | *
11 | * @author chhuang@microsoft.com
12 | */
13 | public class DatabaseHelper extends SQLiteOpenHelper {
14 | public static final String DB_NAME = "article.db";
15 | public static final int VERSION = 3;
16 | private final static String TAG = DatabaseHelper.class.getName();
17 |
18 | public DatabaseHelper(
19 | Context context) {
20 | super(context, DB_NAME, null, VERSION);
21 | }
22 |
23 | @Override
24 | public void onCreate(SQLiteDatabase db) {
25 | ArticleInfo.TABLE.create(db);
26 | }
27 |
28 | @Override
29 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
30 | ArticleInfo.TABLE.delete(db);
31 | ArticleInfo.TABLE.create(db);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/sql/Column.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.sql;
2 |
3 | import android.provider.BaseColumns;
4 |
5 | /**
6 | * Date: 2014/5/27
7 | * Time: 13:48
8 | *
9 | * @author chhuang@microsoft.com
10 | */
11 | public class Column implements BaseColumns {
12 | private String name;
13 | private String constraint;
14 | private DataType type;
15 |
16 | public Column(String name, String constraint, DataType type) {
17 | this.name = name;
18 | this.constraint = constraint;
19 | this.type = type;
20 | }
21 |
22 | public String getName() {
23 | return name;
24 | }
25 |
26 | public String getConstraint() {
27 | return constraint;
28 | }
29 |
30 | public DataType getType() {
31 | return type;
32 | }
33 |
34 | public static enum DataType {
35 | NULL,
36 | INTEGER,
37 | REAL,
38 | TEXT,
39 | BLOB,
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/novel/src/main/java/com/chhuang/novel/data/sql/SQLiteTable.java:
--------------------------------------------------------------------------------
1 | package com.chhuang.novel.data.sql;
2 |
3 | import android.database.sqlite.SQLiteDatabase;
4 | import android.text.TextUtils;
5 | import android.util.Log;
6 |
7 | import java.text.MessageFormat;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | /**
12 | * Date: 2014/5/27
13 | * Time: 13:56
14 | *
15 | * @author chhuang@microsoft.com
16 | */
17 | public class SQLiteTable {
18 | private static final String TAG = SQLiteTable.class.getName();
19 | private String tableName;
20 | private List columnDefinitions;
21 | private List uniqueColumns;
22 |
23 | public SQLiteTable(String tableName) {
24 | this.tableName = tableName;
25 | columnDefinitions = new ArrayList();
26 | columnDefinitions.add(new Column(Column._ID, "PRIMARY KEY", Column.DataType.INTEGER));
27 | uniqueColumns = new ArrayList();
28 | }
29 |
30 | public SQLiteTable addUniqueColumns(String... columns) {
31 | uniqueColumns.add(columns);
32 | return this;
33 | }
34 |
35 | public SQLiteTable addColumn(String name, Column.DataType type) {
36 | return addColumn(name, null, type);
37 | }
38 |
39 | public SQLiteTable addColumn(String name, String constraint, Column.DataType type) {
40 | return addColumn(new Column(name, constraint, type));
41 | }
42 |
43 | public SQLiteTable addColumn(Column column) {
44 | columnDefinitions.add(column);
45 | return this;
46 | }
47 |
48 | public void create(SQLiteDatabase db) {
49 | String formatter = " %s";
50 | StringBuilder buffer = new StringBuilder();
51 | buffer.append("CREATE TABLE IF NOT EXISTS ");
52 | buffer.append(tableName);
53 | buffer.append("(");
54 | int columnCount = columnDefinitions.size();
55 | int index = 0;
56 | for (Column columnDefinition : columnDefinitions) {
57 | buffer.append(columnDefinition.getName()).append(
58 | String.format(formatter, columnDefinition.getType().name()));
59 | String constraint = columnDefinition.getConstraint();
60 |
61 | if (constraint != null) {
62 | buffer.append(String.format(formatter, constraint));
63 | }
64 | if (index < columnCount - 1) {
65 | buffer.append(",");
66 | }
67 | index++;
68 | }
69 | for (String[] unique : uniqueColumns) {
70 | buffer.append(MessageFormat.format(", UNIQUE ({0}) ON CONFLICT REPLACE",
71 | TextUtils.join(", ", unique)));
72 | }
73 | buffer.append(");");
74 | Log.d(TAG, "Creation: " + buffer);
75 | db.execSQL(buffer.toString());
76 | }
77 |
78 | public void delete(final SQLiteDatabase db) {
79 | db.execSQL("DROP TABLE IF EXISTS " + tableName);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/novel/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangcd/novel/8409e97819a7936c1c6d83003a86b25fdb91a069/novel/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/novel/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangcd/novel/8409e97819a7936c1c6d83003a86b25fdb91a069/novel/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/novel/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangcd/novel/8409e97819a7936c1c6d83003a86b25fdb91a069/novel/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/novel/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangcd/novel/8409e97819a7936c1c6d83003a86b25fdb91a069/novel/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/novel/src/main/res/layout/activity_article.xml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
18 |
19 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/novel/src/main/res/layout/activity_directory.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
13 |
14 |
20 |
21 |
22 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/novel/src/main/res/layout/drawer_sidebar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
20 |
21 |
29 |
30 |
--------------------------------------------------------------------------------
/novel/src/main/res/layout/title_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
20 |
21 |
31 |
32 |
44 |
45 |
58 |
59 |
--------------------------------------------------------------------------------
/novel/src/main/res/menu/article.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/novel/src/main/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/novel/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/novel/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/novel/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #66000000
4 |
5 |
6 |
--------------------------------------------------------------------------------
/novel/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
7 |
--------------------------------------------------------------------------------
/novel/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 小说阅读
5 | Dummy Button
6 |
7 | ArticleActivity
8 | Hello world!
9 | Settings
10 | 小说:
11 | open
12 | close
13 |
14 |
15 |
--------------------------------------------------------------------------------
/novel/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
15 |
16 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':novel'
--------------------------------------------------------------------------------