├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── fabric.properties ├── keystore │ └── debug.keystore ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── be │ │ └── neodigi │ │ └── androidboilerplate │ │ ├── MainActivityTest.java │ │ ├── runner │ │ ├── RxAndroidJUnitRunner.java │ │ └── UnlockDeviceAndroidJUnitRunner.java │ │ └── util │ │ ├── RxIdlingExecutionHook.java │ │ └── RxIdlingResource.java │ ├── commonTest │ └── java │ │ └── be │ │ └── neodigi │ │ └── androidboilerplate │ │ └── test │ │ └── common │ │ ├── TestComponentRule.java │ │ ├── TestDataFactory.java │ │ └── injection │ │ ├── component │ │ └── TestComponent.java │ │ └── module │ │ └── ApplicationTestModule.java │ ├── debug │ └── AndroidManifest.xml │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── be │ │ │ └── neodigi │ │ │ └── androidboilerplate │ │ │ ├── BoilerplateApplication.java │ │ │ ├── data │ │ │ ├── DataManager.java │ │ │ ├── SyncService.java │ │ │ ├── local │ │ │ │ ├── DatabaseHelper.java │ │ │ │ └── PreferencesHelper.java │ │ │ ├── model │ │ │ │ └── User.java │ │ │ └── remote │ │ │ │ └── RestService.java │ │ │ ├── injection │ │ │ ├── ActivityContext.java │ │ │ ├── ApplicationContext.java │ │ │ ├── ConfigPersistent.java │ │ │ ├── component │ │ │ │ ├── ActivityComponent.java │ │ │ │ ├── ApplicationComponent.java │ │ │ │ └── ConfigPersistentComponent.java │ │ │ ├── module │ │ │ │ ├── ActivityModule.java │ │ │ │ ├── ApplicationModule.java │ │ │ │ └── RestModule.java │ │ │ └── scope │ │ │ │ └── PerActivity.java │ │ │ ├── ui │ │ │ ├── base │ │ │ │ ├── BaseActivity.java │ │ │ │ ├── BasePresenter.java │ │ │ │ ├── MvpView.java │ │ │ │ └── Presenter.java │ │ │ └── main │ │ │ │ ├── MainActivity.java │ │ │ │ ├── MainMvpView.java │ │ │ │ ├── MainPresenter.java │ │ │ │ └── UsersAdapter.java │ │ │ └── util │ │ │ ├── AndroidComponentUtil.java │ │ │ ├── DialogFactory.java │ │ │ ├── NetworkUtil.java │ │ │ ├── RxEventBus.java │ │ │ ├── RxUtil.java │ │ │ └── ViewUtil.java │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ └── item_ribot.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── be │ └── neodigi │ └── androidboilerplate │ ├── DataManagerTest.java │ ├── DatabaseHelperTest.java │ ├── MainPresenterTest.java │ └── util │ ├── DefaultConfig.java │ ├── RxEventBusTest.java │ └── RxSchedulersOverrideRule.java ├── build.gradle ├── config └── quality │ ├── checkstyle │ └── checkstyle-config.xml │ ├── findbugs │ └── android-exclude-filter.xml │ ├── pmd │ └── pmd-ruleset.xml │ └── quality.gradle ├── crashlytics_release_notes.txt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images └── check-task-diagram.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | .DS_Store 5 | /build 6 | .idea/ 7 | *iml 8 | *.iml 9 | */build -------------------------------------------------------------------------------- /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 2015 Ribot Ltd. 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. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Boilerplate 2 | 3 | Sample Android app that demonstrates the architecture, tools and guidelines that we use when developing for the Android platform (https://github.com/user/android-guidelines) 4 | 5 | 6 | Libraries and tools included: 7 | 8 | - Support libraries 9 | - RecyclerViews and CardViews 10 | - [RxJava](https://github.com/ReactiveX/RxJava) and [RxAndroid](https://github.com/ReactiveX/RxAndroid) 11 | - [Retrofit 2](http://square.github.io/retrofit/) 12 | - [Dagger 2](http://google.github.io/dagger/) 13 | - [Realm](https://realm.io) 14 | - [Butterknife](https://github.com/JakeWharton/butterknife) 15 | - [Timber](https://github.com/JakeWharton/timber) 16 | - [Picasso](http://square.github.io/picasso/) 17 | - [Otto](http://square.github.io/otto/) event bus 18 | - Functional tests with [Espresso](https://code.google.com/p/android-test-kit/wiki/Espresso) 19 | - [Robolectric](http://robolectric.org/) 20 | - [Mockito](http://mockito.org/) 21 | - [Checkstyle](http://checkstyle.sourceforge.net/), [PMD](https://pmd.github.io/) and [Findbugs](http://findbugs.sourceforge.net/) for code analysis 22 | 23 | 24 | ## Architecture 25 | 26 | This project follows user's Android architecture guidelines that are based on [MVP (Model View Presenter)](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter). Read more about them [here](https://github.com/user/android-guidelines/blob/master/architecture_guidelines/android_architecture.md). 27 | 28 | ![](https://github.com/ribot/android-guidelines/raw/master/architecture_guidelines/architecture_diagram.png) 29 | 30 | ### How to implement a new screen following MVP 31 | 32 | Imagine you have to implement a sign in screen. 33 | 34 | 1. Create a new package under `ui` called `signin` 35 | 2. Create an new Activity called `ActivitySignIn`. You could also use a Fragment. 36 | 3. Define the view interface that your Activity is going to implement. Create a new interface called `SignInMvpView` that extends `MvpView`. Add the methods that you think will be necessary, e.g. `showSignInSuccessful()` 37 | 4. Create a `SignInPresenter` class that extends `BasePresenter` 38 | 5. Implement the methods in `SignInPresenter` that your Activity requires to perform the necessary actions, e.g. `signIn(String email)`. Once the sign in action finishes you should call `getMvpView().showSignInSuccessful()`. 39 | 6. Create a `SignInPresenterTest`and write unit tests for `signIn(email)`. Remember to mock the `SignInMvpView` and also the `DataManager`. 40 | 7. Make your `ActivitySignIn` implement `SignInMvpView` and implement the required methods like `showSignInSuccessful()` 41 | 8. In your activity, inject a new instance of `SignInPresenter` and call `presenter.attachView(this)` from `onCreate` and `presenter.detachView()` from `onDestroy()`. Also, set up a click listener in your button that calls `presenter.signIn(email)`. 42 | 43 | ## Code Quality 44 | 45 | This project integrates a combination of unit tests, functional test and code analysis tools. 46 | 47 | ### Tests 48 | 49 | To run **unit** tests on your machine: 50 | 51 | ``` 52 | ./gradlew test 53 | ``` 54 | 55 | To run **functional** tests on connected devices: 56 | 57 | ``` 58 | ./gradlew connectedAndroidTest 59 | ``` 60 | 61 | Note: For Android Studio to use syntax highlighting for Automated tests and Unit tests you **must** switch the Build Variant to the desired mode. 62 | 63 | ### Code Analysis tools 64 | 65 | The following code analysis tools are set up on this project: 66 | 67 | * [PMD](https://pmd.github.io/): It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth. See [this project's PMD ruleset](config/quality/pmd/pmd-ruleset.xml). 68 | 69 | ``` 70 | ./gradlew pmd 71 | ``` 72 | 73 | * [Findbugs](http://findbugs.sourceforge.net/): This tool uses static analysis to find bugs in Java code. Unlike PMD, it uses compiled Java bytecode instead of source code. 74 | 75 | ``` 76 | ./gradlew findbugs 77 | ``` 78 | 79 | * [Checkstyle](http://checkstyle.sourceforge.net/): It ensures that the code style follows [our Android code guidelines](https://github.com/user/android-guidelines/blob/master/project_and_code_guidelines.md#2-code-guidelines). See our [checkstyle config file](config/quality/checkstyle/checkstyle-config.xml). 80 | 81 | ``` 82 | ./gradlew checkstyle 83 | ``` 84 | 85 | ### The check task 86 | 87 | To ensure that your code is valid and stable use check: 88 | 89 | ``` 90 | ./gradlew check 91 | ``` 92 | 93 | This will run all the code analysis tools and unit tests in the following order: 94 | 95 | ![Check Diagram](images/check-task-diagram.png) 96 | 97 | ## Distribution 98 | 99 | The project can be distributed using either [Crashlytics](http://support.crashlytics.com/knowledgebase/articles/388925-beta-distributions-with-gradle) or the [Google Play Store](https://github.com/Triple-T/gradle-play-publisher). 100 | 101 | ### Play Store 102 | 103 | We use the __Gradle Play Publisher__ plugin. Once set up correctly, you will be able to push new builds to 104 | the Alpha, Beta or production channels like this 105 | 106 | ``` 107 | ./gradlew publishApkRelease 108 | ``` 109 | Read [plugin documentation](https://github.com/Triple-T/gradle-play-publisher) for more info. 110 | 111 | ### Crashlytics 112 | 113 | You can also use Fabric's Crashlytics for distributing beta releases. Remember to add your fabric 114 | account details to `app/src/fabric.properties`. 115 | 116 | To upload a release build to Crashlytics run: 117 | 118 | ``` 119 | ./gradlew assembleRelease crashlyticsUploadDistributionRelease 120 | ``` 121 | 122 | ## New project setup 123 | 124 | To quickly start a new project from this boilerplate follow the next steps: 125 | 126 | * Download this [repository as a zip](https://github.com/user/android-boilerplate/archive/master.zip). 127 | * Change the package name. 128 | * Rename packages in main, androidTest and test using Android Studio. 129 | * In `app/build.gradle` file, `packageName` and `testInstrumentationRunner`. 130 | * In `src/main/AndroidManifest.xml` and `src/debug/AndroidManifest.xml`. 131 | * Create a new git repository, [see GitHub tutorial](https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/). 132 | * Replace the example code with your app code following the same architecture. 133 | * In `app/build.gradle` add the signing config to enable release versions. 134 | * Add Fabric API key and secret to fabric.properties and uncomment Fabric plugin set up in `app/build.gradle` 135 | * Update `proguard-rules.pro` to keep models (see TODO in file) and add extra rules to file if needed. 136 | * Update README with information relevant to the new project. 137 | * Update LICENSE to match the requirements of the new project. 138 | 139 | ## License 140 | 141 | ``` 142 | Licensed under the Apache License, Version 2.0 (the "License"); 143 | you may not use this file except in compliance with the License. 144 | You may obtain a copy of the License at 145 | 146 | http://www.apache.org/licenses/LICENSE-2.0 147 | 148 | Unless required by applicable law or agreed to in writing, software 149 | distributed under the License is distributed on an "AS IS" BASIS, 150 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 151 | See the License for the specific language governing permissions and 152 | limitations under the License. 153 | ``` 154 | 155 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | *iml 3 | *.iml 4 | .idea -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply from: '../config/quality/quality.gradle' 3 | apply plugin: 'com.github.triplet.play' 4 | apply plugin: 'realm-android' 5 | apply plugin: 'com.neenbedankt.android-apt' 6 | //TODO uncomment line below after adding fabric api secret and key to fabric.properties 7 | //apply plugin: 'io.fabric' 8 | 9 | android { 10 | compileSdkVersion 24 11 | buildToolsVersion '24.0.3' 12 | 13 | defaultConfig { 14 | applicationId 'be.neodigi.androidboilerplate' 15 | minSdkVersion 16 16 | targetSdkVersion 24 17 | testInstrumentationRunner "${applicationId}.runner.RxAndroidJUnitRunner" 18 | versionCode 1000 19 | // Major -> Millions, Minor -> Thousands, Bugfix -> Hundreds. E.g 1.3.72 == 1,003,072 20 | versionName '0.1.0' 21 | } 22 | 23 | signingConfigs { 24 | // You must set up an environment var before release signing 25 | // Run: export APP_KEY={password} 26 | // TODO Add your release keystore in /keystore folder 27 | release { 28 | storeFile file('keystore/release.keystore') 29 | keyAlias 'alias' 30 | storePassword "$System.env.APP_KEY" 31 | keyPassword "$System.env.APP_KEY" 32 | } 33 | 34 | debug { 35 | storeFile file('keystore/debug.keystore') 36 | keyAlias 'androiddebugkey' 37 | storePassword 'android' 38 | keyPassword 'android' 39 | } 40 | } 41 | 42 | buildTypes { 43 | release { 44 | signingConfig signingConfigs.release 45 | 46 | minifyEnabled true 47 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 48 | 49 | ext.betaDistributionReleaseNotesFilePath = 50 | file('../crashlytics_release_notes.txt').absolutePath 51 | 52 | buildConfigField "String", "URL_ENDPOINT", "\"http://jsonplaceholder.typicode.com/\"" 53 | } 54 | 55 | debug { 56 | versionNameSuffix " Debug" 57 | debuggable true 58 | 59 | buildConfigField "String", "URL_ENDPOINT", "\"http://jsonplaceholder.typicode.com/\"" 60 | } 61 | } 62 | 63 | sourceSets { 64 | def commonTestDir = 'src/commonTest/java' 65 | test { 66 | java.srcDir commonTestDir 67 | } 68 | androidTest { 69 | java.srcDir commonTestDir 70 | } 71 | } 72 | 73 | //Needed because of this https://github.com/square/okio/issues/58 74 | lintOptions { 75 | warning 'InvalidPackage' 76 | } 77 | } 78 | 79 | play { 80 | serviceAccountEmail = 'your-service-account-email' 81 | pk12File = file('key.p12') 82 | // By default publishes to Alpha channel 83 | track = 'alpha' 84 | } 85 | 86 | dependencies { 87 | final PLAY_SERVICES_VERSION = '9.6.1' 88 | final SUPPORT_LIBRARY_VERSION = '24.2.1' 89 | final RETROFIT_VERSION = '2.1.0' 90 | final OKHTTP_VERSION = '3.4.1' 91 | final DAGGER_VERSION = '2.5' 92 | final PARCELER_VERSION = '1.1.5' 93 | final BUTTERKNIFE_VERSION = '8.1.0' 94 | final DEXMAKER_VERSION = '1.4' 95 | final HAMCREST_VERSION = '1.3' 96 | final POWERMOCK_VERSION = '1.6.4' 97 | final ESPRESSO_VERSION = '2.2.1' 98 | final RUNNER_VERSION = '0.4' 99 | 100 | def daggerCompiler = "com.google.dagger:dagger-compiler:$DAGGER_VERSION" 101 | def jUnit = "junit:junit:4.12" 102 | def mockito = "org.mockito:mockito-core:1.10.19" 103 | 104 | // App Dependencies 105 | compile "com.google.android.gms:play-services-gcm:$PLAY_SERVICES_VERSION" 106 | compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION" 107 | compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION" 108 | compile "com.android.support:cardview-v7:$SUPPORT_LIBRARY_VERSION" 109 | compile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION" 110 | 111 | compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION" 112 | compile "com.squareup.retrofit2:converter-gson:$RETROFIT_VERSION" 113 | compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION" 114 | compile "com.squareup.okhttp3:okhttp:$OKHTTP_VERSION" 115 | compile "com.squareup.okhttp3:logging-interceptor:$OKHTTP_VERSION" 116 | 117 | compile 'com.squareup.picasso:picasso:2.5.2' 118 | compile 'io.reactivex:rxandroid:1.2.1' 119 | compile 'io.reactivex:rxjava:1.1.6' 120 | compile('com.crashlytics.sdk.android:crashlytics:2.5.7@aar') { 121 | transitive = true; 122 | } 123 | 124 | compile "org.parceler:parceler-api:$PARCELER_VERSION" 125 | apt "org.parceler:parceler:$PARCELER_VERSION" 126 | 127 | compile 'com.jakewharton.timber:timber:4.1.2' 128 | compile "com.jakewharton:butterknife:$BUTTERKNIFE_VERSION" 129 | apt "com.jakewharton:butterknife-compiler:$BUTTERKNIFE_VERSION" 130 | 131 | compile "com.google.dagger:dagger:$DAGGER_VERSION" 132 | provided 'org.glassfish:javax.annotation:10.0-b28' //Required by Dagger2 133 | apt daggerCompiler 134 | testApt daggerCompiler 135 | androidTestApt daggerCompiler 136 | 137 | // Instrumentation test dependencies 138 | androidTestCompile jUnit 139 | androidTestCompile mockito 140 | androidTestCompile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION" 141 | androidTestCompile("com.android.support.test.espresso:espresso-contrib:$ESPRESSO_VERSION") { 142 | exclude group: 'com.android.support', module: 'appcompat' 143 | exclude group: 'com.android.support', module: 'support-v4' 144 | exclude group: 'com.android.support', module: 'recyclerview-v7' 145 | } 146 | androidTestCompile "com.android.support.test.espresso:espresso-core:$ESPRESSO_VERSION" 147 | androidTestCompile "com.android.support.test:runner:$RUNNER_VERSION" 148 | androidTestCompile "com.android.support.test:rules:$RUNNER_VERSION" 149 | androidTestCompile "com.crittercism.dexmaker:dexmaker:$DEXMAKER_VERSION" 150 | androidTestCompile "com.crittercism.dexmaker:dexmaker-dx:$DEXMAKER_VERSION" 151 | androidTestCompile "com.crittercism.dexmaker:dexmaker-mockito:$DEXMAKER_VERSION" 152 | 153 | // Unit tests dependencies 154 | testCompile jUnit 155 | testCompile mockito 156 | testCompile 'org.powermock:powermock-core:1.6.4' 157 | testCompile "org.powermock:powermock-module-junit4:$POWERMOCK_VERSION" 158 | testCompile "org.powermock:powermock-module-junit4-rule:$POWERMOCK_VERSION" 159 | testCompile "org.powermock:powermock-api-mockito:$POWERMOCK_VERSION" 160 | testCompile "org.powermock:powermock-classloading-xstream:$POWERMOCK_VERSION" 161 | testCompile "org.hamcrest:hamcrest-core:$HAMCREST_VERSION" 162 | testCompile "org.hamcrest:hamcrest-library:$HAMCREST_VERSION" 163 | testCompile "org.hamcrest:hamcrest-integration:$HAMCREST_VERSION" 164 | testCompile 'org.robolectric:robolectric:3.1' 165 | } 166 | 167 | // Log out test results to console 168 | tasks.matching {it instanceof Test}.all { 169 | testLogging.events = ["failed", "passed", "skipped"] 170 | } 171 | 172 | 173 | -------------------------------------------------------------------------------- /app/fabric.properties: -------------------------------------------------------------------------------- 1 | apiSecret=changeMeToYourRealApiSecret 2 | apiKey=changeMeToYourRealApiKey -------------------------------------------------------------------------------- /app/keystore/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/app/keystore/debug.keystore -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 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 | #} 18 | 19 | # Retrofit rules 20 | -dontwarn retrofit2.** 21 | -keep class retrofit2.** { *; } 22 | -keepattributes Signature 23 | -keepattributes Exceptions 24 | 25 | -keepclasseswithmembers class * { 26 | @retrofit2.http.* ; 27 | } 28 | 29 | # OkHttp rules 30 | -dontwarn okio.** 31 | -dontwarn com.squareup.okhttp.** 32 | 33 | # Otto rules 34 | -keepclassmembers class ** { 35 | @com.squareup.otto.Subscribe public *; 36 | @com.squareup.otto.Produce public *; 37 | } 38 | 39 | # RxJava rules 40 | # RxAndroid will soon ship with rules so this may not be needed in the future 41 | # https://github.com/ReactiveX/RxAndroid/issues/219 42 | -dontwarn sun.misc.Unsafe 43 | -keep class rx.internal.util.unsafe.** { *; } 44 | 45 | # Gson rules 46 | -keepattributes Signature 47 | -keep class sun.misc.Unsafe { *; } 48 | # TODO change to match your package model 49 | # Keep non static or private fields of models so Gson can find their names 50 | -keepclassmembers class be.neodigi.androidboilerplate.data.model.** { 51 | !static !private ; 52 | } 53 | # TODO change to match your Retrofit services (only if using inner models withing the service) 54 | # Some models used by gson are inner classes inside the retrofit service 55 | -keepclassmembers class be.neodigi.androidboilerplate.data.remote.RestService$** { 56 | !static !private ; 57 | } 58 | 59 | # Parcel library 60 | -keep interface org.parceler.Parcel 61 | -keep @org.parceler.Parcel class * { *; } 62 | -keep class **$$Parcelable { *; } 63 | 64 | # Produces useful obfuscated stack traces 65 | # http://proguard.sourceforge.net/manual/examples.html#stacktrace 66 | -renamesourcefileattribute SourceFile 67 | -keepattributes SourceFile,LineNumberTable 68 | -------------------------------------------------------------------------------- /app/src/androidTest/java/be/neodigi/androidboilerplate/MainActivityTest.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate; 2 | 3 | import android.content.Intent; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.espresso.contrib.RecyclerViewActions; 6 | import android.support.test.rule.ActivityTestRule; 7 | import android.support.test.runner.AndroidJUnit4; 8 | 9 | import org.junit.Rule; 10 | import org.junit.Test; 11 | import org.junit.rules.RuleChain; 12 | import org.junit.rules.TestRule; 13 | import org.junit.runner.RunWith; 14 | 15 | import java.util.List; 16 | 17 | import be.neodigi.androidboilerplate.data.model.User; 18 | import be.neodigi.androidboilerplate.test.common.TestDataFactory; 19 | import be.neodigi.androidboilerplate.test.common.TestComponentRule; 20 | import be.neodigi.androidboilerplate.ui.main.MainActivity; 21 | import rx.Observable; 22 | 23 | import static android.support.test.espresso.Espresso.onView; 24 | import static android.support.test.espresso.assertion.ViewAssertions.matches; 25 | import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; 26 | import static android.support.test.espresso.matcher.ViewMatchers.withId; 27 | import static android.support.test.espresso.matcher.ViewMatchers.withText; 28 | import static org.mockito.Mockito.when; 29 | 30 | @RunWith(AndroidJUnit4.class) 31 | public class MainActivityTest { 32 | 33 | public final TestComponentRule component = 34 | new TestComponentRule(InstrumentationRegistry.getTargetContext()); 35 | public final ActivityTestRule main = 36 | new ActivityTestRule(MainActivity.class, false, false) { 37 | @Override 38 | protected Intent getActivityIntent() { 39 | // Override the default intent so we pass a false flag for syncing so it doesn't 40 | // start a sync service in the background that would affect the behaviour of 41 | // this test. 42 | return MainActivity.getStartIntent( 43 | InstrumentationRegistry.getTargetContext(), false); 44 | } 45 | }; 46 | 47 | // TestComponentRule needs to go first to make sure the Dagger ApplicationTestComponent is set 48 | // in the Application before any Activity is launched. 49 | @Rule 50 | public final TestRule chain = RuleChain.outerRule(component).around(main); 51 | 52 | @Test 53 | public void listOfUsersShows() { 54 | List testDataUsers = TestDataFactory.makeListUsers(20); 55 | when(component.getMockDataManager().getUsers()) 56 | .thenReturn(Observable.just(testDataUsers)); 57 | 58 | main.launchActivity(null); 59 | 60 | int position = 0; 61 | for (User user : testDataUsers) { 62 | onView(withId(R.id.recycler_view)) 63 | .perform(RecyclerViewActions.scrollToPosition(position)); 64 | String name = String.format("%s %s", user.getUsername(), 65 | user.getName()); 66 | onView(withText(name)) 67 | .check(matches(isDisplayed())); 68 | onView(withText(user.getEmail())) 69 | .check(matches(isDisplayed())); 70 | position++; 71 | } 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /app/src/androidTest/java/be/neodigi/androidboilerplate/runner/RxAndroidJUnitRunner.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.runner; 2 | 3 | import android.os.Bundle; 4 | import android.support.test.espresso.Espresso; 5 | 6 | import be.neodigi.androidboilerplate.util.RxIdlingExecutionHook; 7 | import be.neodigi.androidboilerplate.util.RxIdlingResource; 8 | import rx.plugins.RxJavaPlugins; 9 | 10 | /** 11 | * Runner that registers a Espresso Indling resource that handles waiting for 12 | * RxJava Observables to finish. 13 | * WARNING - Using this runner will block the tests if the application uses long-lived hot 14 | * Observables such us event buses, etc. 15 | */ 16 | public class RxAndroidJUnitRunner extends UnlockDeviceAndroidJUnitRunner { 17 | 18 | @Override 19 | public void onCreate(Bundle arguments) { 20 | super.onCreate(arguments); 21 | RxIdlingResource rxIdlingResource = new RxIdlingResource(); 22 | RxJavaPlugins.getInstance() 23 | .registerObservableExecutionHook(new RxIdlingExecutionHook(rxIdlingResource)); 24 | Espresso.registerIdlingResources(rxIdlingResource); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/androidTest/java/be/neodigi/androidboilerplate/runner/UnlockDeviceAndroidJUnitRunner.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.runner; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Application; 5 | import android.app.KeyguardManager; 6 | import android.os.PowerManager; 7 | import android.support.test.runner.AndroidJUnitRunner; 8 | 9 | import static android.content.Context.KEYGUARD_SERVICE; 10 | import static android.content.Context.POWER_SERVICE; 11 | import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP; 12 | import static android.os.PowerManager.FULL_WAKE_LOCK; 13 | import static android.os.PowerManager.ON_AFTER_RELEASE; 14 | 15 | /** 16 | * Extension of AndroidJUnitRunner that adds some functionality to unblock the device screen 17 | * before starting the tests. 18 | */ 19 | public class UnlockDeviceAndroidJUnitRunner extends AndroidJUnitRunner { 20 | 21 | private PowerManager.WakeLock mWakeLock; 22 | 23 | @Override 24 | @SuppressLint("MissingPermission") 25 | public void onStart() { 26 | Application application = (Application) getTargetContext().getApplicationContext(); 27 | String simpleName = UnlockDeviceAndroidJUnitRunner.class.getSimpleName(); 28 | // Unlock the device so that the tests can input keystrokes. 29 | ((KeyguardManager) application.getSystemService(KEYGUARD_SERVICE)) 30 | .newKeyguardLock(simpleName) 31 | .disableKeyguard(); 32 | // Wake up the screen. 33 | PowerManager powerManager = (PowerManager) application.getSystemService(POWER_SERVICE); 34 | mWakeLock = powerManager.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | 35 | ON_AFTER_RELEASE, simpleName); 36 | mWakeLock.acquire(); 37 | super.onStart(); 38 | } 39 | 40 | @Override 41 | public void onDestroy() { 42 | mWakeLock.release(); 43 | super.onDestroy(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /app/src/androidTest/java/be/neodigi/androidboilerplate/util/RxIdlingExecutionHook.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import rx.Observable; 4 | import rx.Subscription; 5 | import rx.plugins.RxJavaObservableExecutionHook; 6 | 7 | /** 8 | * RxJava Observable execution hook that handles updating the active subscription 9 | * count for a given Espresso RxIdlingResource. 10 | */ 11 | public class RxIdlingExecutionHook extends RxJavaObservableExecutionHook { 12 | 13 | private RxIdlingResource mRxIdlingResource; 14 | 15 | public RxIdlingExecutionHook(RxIdlingResource rxIdlingResource) { 16 | mRxIdlingResource = rxIdlingResource; 17 | } 18 | 19 | @Override 20 | public Observable.OnSubscribe onSubscribeStart( 21 | Observable observableInstance, Observable.OnSubscribe onSubscribe) { 22 | mRxIdlingResource.incrementActiveSubscriptionsCount(); 23 | return super.onSubscribeStart(observableInstance, onSubscribe); 24 | } 25 | 26 | @Override 27 | public Throwable onSubscribeError(Throwable e) { 28 | mRxIdlingResource.decrementActiveSubscriptionsCount(); 29 | return super.onSubscribeError(e); 30 | } 31 | 32 | @Override 33 | public Subscription onSubscribeReturn(Subscription subscription) { 34 | mRxIdlingResource.decrementActiveSubscriptionsCount(); 35 | return super.onSubscribeReturn(subscription); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/androidTest/java/be/neodigi/androidboilerplate/util/RxIdlingResource.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import android.support.test.espresso.IdlingResource; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import timber.log.Timber; 8 | 9 | /** 10 | * Espresso Idling resource that handles waiting for RxJava Observables executions. 11 | * This class must be used with RxIdlingExecutionHook. 12 | * Before registering this idling resource you must: 13 | * 1. Create an instance of RxIdlingExecutionHook by passing an instance of this class. 14 | * 2. Register RxIdlingExecutionHook with the RxJavaPlugins using registerObservableExecutionHook() 15 | * 3. Register this idle resource with Espresso using Espresso.registerIdlingResources() 16 | */ 17 | public class RxIdlingResource implements IdlingResource { 18 | 19 | private final AtomicInteger mActiveSubscriptionsCount = new AtomicInteger(0); 20 | private ResourceCallback mResourceCallback; 21 | 22 | @Override 23 | public String getName() { 24 | return getClass().getSimpleName(); 25 | } 26 | 27 | @Override 28 | public boolean isIdleNow() { 29 | return mActiveSubscriptionsCount.get() == 0; 30 | } 31 | 32 | @Override 33 | public void registerIdleTransitionCallback(ResourceCallback callback) { 34 | mResourceCallback = callback; 35 | } 36 | 37 | public void incrementActiveSubscriptionsCount() { 38 | int count = mActiveSubscriptionsCount.incrementAndGet(); 39 | Timber.i("Active subscriptions count increased to %d", count); 40 | } 41 | 42 | public void decrementActiveSubscriptionsCount() { 43 | int count = mActiveSubscriptionsCount.decrementAndGet(); 44 | Timber.i("Active subscriptions count decreased to %d", count); 45 | if (isIdleNow()) { 46 | Timber.i("There is no active subscriptions, transitioning to Idle"); 47 | mResourceCallback.onTransitionToIdle(); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /app/src/commonTest/java/be/neodigi/androidboilerplate/test/common/TestComponentRule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.test.common; 2 | 3 | import android.content.Context; 4 | 5 | import org.junit.rules.TestRule; 6 | import org.junit.runner.Description; 7 | import org.junit.runners.model.Statement; 8 | 9 | import be.neodigi.androidboilerplate.BoilerplateApplication; 10 | import be.neodigi.androidboilerplate.data.DataManager; 11 | import be.neodigi.androidboilerplate.test.common.injection.component.DaggerTestComponent; 12 | import be.neodigi.androidboilerplate.test.common.injection.component.TestComponent; 13 | import be.neodigi.androidboilerplate.test.common.injection.module.ApplicationTestModule; 14 | 15 | /** 16 | * Test rule that creates and sets a Dagger TestComponent into the application overriding the 17 | * existing application component. 18 | * Use this rule in your test case in order for the app to use mock dependencies. 19 | * It also exposes some of the dependencies so they can be easily accessed from the tests, e.g. to 20 | * stub mocks etc. 21 | */ 22 | public class TestComponentRule implements TestRule { 23 | 24 | private final TestComponent mTestComponent; 25 | private final Context mContext; 26 | 27 | public TestComponentRule(Context context) { 28 | mContext = context; 29 | BoilerplateApplication application = BoilerplateApplication.get(context); 30 | mTestComponent = DaggerTestComponent.builder() 31 | .applicationTestModule(new ApplicationTestModule(application)) 32 | .build(); 33 | } 34 | 35 | public Context getContext() { 36 | return mContext; 37 | } 38 | 39 | public DataManager getMockDataManager() { 40 | return mTestComponent.dataManager(); 41 | } 42 | 43 | @Override 44 | public Statement apply(final Statement base, Description description) { 45 | return new Statement() { 46 | @Override 47 | public void evaluate() throws Throwable { 48 | BoilerplateApplication application = BoilerplateApplication.get(mContext); 49 | application.setComponent(mTestComponent); 50 | base.evaluate(); 51 | application.setComponent(null); 52 | } 53 | }; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/src/commonTest/java/be/neodigi/androidboilerplate/test/common/TestDataFactory.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.test.common; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.UUID; 6 | 7 | import be.neodigi.androidboilerplate.data.model.User; 8 | 9 | /** 10 | * Factory class that makes instances of data models with random field values. 11 | * The aim of this class is to help setting up test fixtures. 12 | */ 13 | public class TestDataFactory { 14 | 15 | public static String randomUuid() { 16 | return UUID.randomUUID().toString(); 17 | } 18 | 19 | public static User makeUser(String uniqueSuffix) { 20 | User u = new User(); 21 | u.setId(1); 22 | u.setName(uniqueSuffix); 23 | u.setEmail(uniqueSuffix); 24 | u.setUsername(uniqueSuffix); 25 | return u; 26 | } 27 | 28 | public static List makeListUsers(int number) { 29 | List users = new ArrayList<>(); 30 | for (int i = 0; i < number; i++) { 31 | users.add(makeUser(String.valueOf(i))); 32 | } 33 | return users; 34 | } 35 | } -------------------------------------------------------------------------------- /app/src/commonTest/java/be/neodigi/androidboilerplate/test/common/injection/component/TestComponent.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.test.common.injection.component; 2 | 3 | import javax.inject.Singleton; 4 | 5 | import be.neodigi.androidboilerplate.injection.component.ApplicationComponent; 6 | import be.neodigi.androidboilerplate.test.common.injection.module.ApplicationTestModule; 7 | import dagger.Component; 8 | 9 | @Singleton 10 | @Component(modules = ApplicationTestModule.class) 11 | public interface TestComponent extends ApplicationComponent { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /app/src/commonTest/java/be/neodigi/androidboilerplate/test/common/injection/module/ApplicationTestModule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.test.common.injection.module; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import javax.inject.Singleton; 7 | 8 | import be.neodigi.androidboilerplate.data.DataManager; 9 | import be.neodigi.androidboilerplate.data.remote.RestService; 10 | import be.neodigi.androidboilerplate.injection.ApplicationContext; 11 | import dagger.Module; 12 | import dagger.Provides; 13 | import io.realm.Realm; 14 | 15 | import static org.mockito.Mockito.mock; 16 | 17 | /** 18 | * Provides application-level dependencies for an app running on a testing environment 19 | * This allows injecting mocks if necessary. 20 | */ 21 | @Module 22 | public class ApplicationTestModule { 23 | 24 | private final Application mApplication; 25 | 26 | public ApplicationTestModule(Application application) { 27 | mApplication = application; 28 | } 29 | 30 | @Provides 31 | Application provideApplication() { 32 | return mApplication; 33 | } 34 | 35 | @Provides 36 | @ApplicationContext 37 | Context provideContext() { 38 | return mApplication; 39 | } 40 | 41 | @Provides 42 | Realm provideRealm() { 43 | return Realm.getDefaultInstance(); 44 | } 45 | 46 | /************* MOCKS *************/ 47 | 48 | @Provides 49 | @Singleton 50 | DataManager provideDataManager() { 51 | return mock(DataManager.class); 52 | } 53 | 54 | @Provides 55 | @Singleton 56 | RestService provideRestService() { 57 | return mock(RestService.class); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/BoilerplateApplication.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import com.crashlytics.android.Crashlytics; 7 | 8 | import be.neodigi.androidboilerplate.injection.component.ApplicationComponent; 9 | import be.neodigi.androidboilerplate.injection.component.DaggerApplicationComponent; 10 | import be.neodigi.androidboilerplate.injection.module.ApplicationModule; 11 | import io.fabric.sdk.android.Fabric; 12 | import timber.log.Timber; 13 | 14 | public class BoilerplateApplication extends Application { 15 | 16 | ApplicationComponent mApplicationComponent; 17 | 18 | @Override 19 | public void onCreate() { 20 | super.onCreate(); 21 | 22 | if (BuildConfig.DEBUG) { 23 | Timber.plant(new Timber.DebugTree()); 24 | Fabric.with(this, new Crashlytics()); 25 | } 26 | } 27 | 28 | public static BoilerplateApplication get(Context context) { 29 | return (BoilerplateApplication) context.getApplicationContext(); 30 | } 31 | 32 | public ApplicationComponent getComponent() { 33 | if (mApplicationComponent == null) { 34 | mApplicationComponent = DaggerApplicationComponent.builder() 35 | .applicationModule(new ApplicationModule(this)) 36 | .build(); 37 | } 38 | return mApplicationComponent; 39 | } 40 | 41 | // Needed to replace the component with a test specific one 42 | public void setComponent(ApplicationComponent applicationComponent) { 43 | mApplicationComponent = applicationComponent; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/DataManager.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data; 2 | 3 | import java.util.List; 4 | 5 | import javax.inject.Inject; 6 | import javax.inject.Singleton; 7 | 8 | import be.neodigi.androidboilerplate.data.local.DatabaseHelper; 9 | import be.neodigi.androidboilerplate.data.local.PreferencesHelper; 10 | import be.neodigi.androidboilerplate.data.model.User; 11 | import be.neodigi.androidboilerplate.data.remote.RestService; 12 | import rx.Observable; 13 | import rx.functions.Func1; 14 | 15 | @Singleton 16 | public class DataManager { 17 | 18 | private final RestService mRestService; 19 | private final DatabaseHelper mDatabaseHelper; 20 | private final PreferencesHelper mPreferencesHelper; 21 | 22 | @Inject 23 | public DataManager(RestService restService, PreferencesHelper preferencesHelper, 24 | DatabaseHelper databaseHelper) { 25 | mRestService = restService; 26 | mPreferencesHelper = preferencesHelper; 27 | mDatabaseHelper = databaseHelper; 28 | } 29 | 30 | public PreferencesHelper getPreferencesHelper() { 31 | return mPreferencesHelper; 32 | } 33 | 34 | public Observable syncUsers() { 35 | return mRestService.getUsers() 36 | .concatMap(new Func1, Observable>() { 37 | @Override 38 | public Observable call(List users) { 39 | return mDatabaseHelper.setUsers(users); 40 | } 41 | }); 42 | } 43 | 44 | public Observable> getUsers() { 45 | return mDatabaseHelper.getUsers().distinct(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/SyncService.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data; 2 | 3 | import android.app.Service; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.net.ConnectivityManager; 8 | import android.os.IBinder; 9 | 10 | import javax.inject.Inject; 11 | 12 | import be.neodigi.androidboilerplate.BoilerplateApplication; 13 | import be.neodigi.androidboilerplate.data.model.User; 14 | import be.neodigi.androidboilerplate.util.AndroidComponentUtil; 15 | import be.neodigi.androidboilerplate.util.NetworkUtil; 16 | import rx.Observer; 17 | import rx.Subscription; 18 | import rx.schedulers.Schedulers; 19 | import timber.log.Timber; 20 | 21 | public class SyncService extends Service { 22 | 23 | @Inject DataManager mDataManager; 24 | private Subscription mSubscription; 25 | 26 | public static Intent getStartIntent(Context context) { 27 | return new Intent(context, SyncService.class); 28 | } 29 | 30 | public static boolean isRunning(Context context) { 31 | return AndroidComponentUtil.isServiceRunning(context, SyncService.class); 32 | } 33 | 34 | @Override 35 | public void onCreate() { 36 | super.onCreate(); 37 | BoilerplateApplication.get(this).getComponent().inject(this); 38 | } 39 | 40 | @Override 41 | public int onStartCommand(Intent intent, int flags, final int startId) { 42 | Timber.i("Starting sync..."); 43 | 44 | if (!NetworkUtil.isNetworkConnected(this)) { 45 | Timber.i("Sync canceled, connection not available"); 46 | AndroidComponentUtil.toggleComponent(this, SyncOnConnectionAvailable.class, true); 47 | stopSelf(startId); 48 | return START_NOT_STICKY; 49 | } 50 | 51 | if (mSubscription != null && !mSubscription.isUnsubscribed()) mSubscription.unsubscribe(); 52 | mSubscription = mDataManager.syncUsers() 53 | .subscribeOn(Schedulers.io()) 54 | .subscribe(new Observer() { 55 | @Override 56 | public void onCompleted() { 57 | Timber.i("Synced successfully!"); 58 | stopSelf(startId); 59 | } 60 | 61 | @Override 62 | public void onError(Throwable e) { 63 | Timber.w(e, "Error syncing."); 64 | stopSelf(startId); 65 | } 66 | 67 | @Override 68 | public void onNext(User user) { 69 | } 70 | }); 71 | 72 | return START_STICKY; 73 | } 74 | 75 | @Override 76 | public void onDestroy() { 77 | if (mSubscription != null) mSubscription.unsubscribe(); 78 | super.onDestroy(); 79 | } 80 | 81 | @Override 82 | public IBinder onBind(Intent intent) { 83 | return null; 84 | } 85 | 86 | public static class SyncOnConnectionAvailable extends BroadcastReceiver { 87 | 88 | @Override 89 | public void onReceive(Context context, Intent intent) { 90 | if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) 91 | && NetworkUtil.isNetworkConnected(context)) { 92 | Timber.i("Connection is now available, triggering sync..."); 93 | AndroidComponentUtil.toggleComponent(context, this.getClass(), false); 94 | context.startService(getStartIntent(context)); 95 | } 96 | } 97 | } 98 | 99 | } -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/local/DatabaseHelper.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data.local; 2 | 3 | import java.util.Collection; 4 | import java.util.List; 5 | 6 | import javax.inject.Inject; 7 | import javax.inject.Provider; 8 | import javax.inject.Singleton; 9 | 10 | import be.neodigi.androidboilerplate.data.model.User; 11 | import io.realm.Realm; 12 | import io.realm.RealmResults; 13 | import rx.Observable; 14 | import rx.Subscriber; 15 | import rx.functions.Func1; 16 | import timber.log.Timber; 17 | 18 | @Singleton 19 | public class DatabaseHelper { 20 | 21 | private final Provider mRealmProvider; 22 | 23 | @Inject 24 | DatabaseHelper(Provider realmProvider) { 25 | mRealmProvider = realmProvider; 26 | } 27 | 28 | public Observable setUsers(final Collection newUsers) { 29 | return Observable.create(new Observable.OnSubscribe() { 30 | @Override 31 | public void call(Subscriber subscriber) { 32 | if (subscriber.isUnsubscribed()) return; 33 | Realm realm = null; 34 | 35 | try { 36 | realm = mRealmProvider.get(); 37 | realm.executeTransaction(new Realm.Transaction() { 38 | @Override 39 | public void execute(Realm realm) { 40 | realm.copyToRealmOrUpdate(newUsers); 41 | } 42 | }); 43 | } catch (Exception e) { 44 | Timber.e(e, "There was an error while adding in Realm."); 45 | subscriber.onError(e); 46 | } finally { 47 | if (realm != null) { 48 | realm.close(); 49 | } 50 | } 51 | } 52 | }); 53 | } 54 | 55 | public Observable> getUsers() { 56 | final Realm realm = mRealmProvider.get(); 57 | return realm.where(User.class).findAllAsync().asObservable() 58 | .filter(new Func1, Boolean>() { 59 | @Override 60 | public Boolean call(RealmResults users) { 61 | return users.isLoaded(); 62 | } 63 | }) 64 | .map(new Func1, List>() { 65 | @Override 66 | public List call(RealmResults users) { 67 | return realm.copyFromRealm(users); 68 | } 69 | }); 70 | } 71 | 72 | /*public Observable> getUsers() { 73 | final Realm realm = mRealmProvider.get(); 74 | RealmResults realmUsers = realm.where(User.class).findAll(); 75 | 76 | realm.beginTransaction(); 77 | List users = realm.copyFromRealm(realmUsers); 78 | realm.commitTransaction(); 79 | 80 | realm.close(); 81 | 82 | return Observable.just(users); 83 | }*/ 84 | } 85 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/local/PreferencesHelper.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data.local; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | import javax.inject.Inject; 7 | import javax.inject.Singleton; 8 | 9 | import be.neodigi.androidboilerplate.injection.ApplicationContext; 10 | 11 | @Singleton 12 | public class PreferencesHelper { 13 | 14 | public static final String PREF_FILE_NAME = "android_boilerplate_pref_file"; 15 | 16 | private final SharedPreferences mPref; 17 | 18 | @Inject 19 | public PreferencesHelper(@ApplicationContext Context context) { 20 | mPref = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); 21 | } 22 | 23 | public void clear() { 24 | mPref.edit().clear().apply(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/model/User.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data.model; 2 | 3 | import org.parceler.Parcel; 4 | 5 | import io.realm.RealmObject; 6 | import io.realm.UserRealmProxy; 7 | import io.realm.annotations.PrimaryKey; 8 | 9 | @Parcel(implementations = { UserRealmProxy.class }, 10 | value = Parcel.Serialization.BEAN, 11 | analyze = { User.class }) 12 | public class User extends RealmObject { 13 | 14 | @PrimaryKey 15 | public int id; 16 | public String name; 17 | public String username; 18 | public String email; 19 | public String phone; 20 | public String website; 21 | 22 | public int getId() { 23 | return id; 24 | } 25 | 26 | public void setId(int id) { 27 | this.id = id; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public String getUsername() { 39 | return username; 40 | } 41 | 42 | public void setUsername(String username) { 43 | this.username = username; 44 | } 45 | 46 | public String getEmail() { 47 | return email; 48 | } 49 | 50 | public void setEmail(String email) { 51 | this.email = email; 52 | } 53 | 54 | public String getPhone() { 55 | return phone; 56 | } 57 | 58 | public void setPhone(String phone) { 59 | this.phone = phone; 60 | } 61 | 62 | public String getWebsite() { 63 | return website; 64 | } 65 | 66 | public void setWebsite(String website) { 67 | this.website = website; 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/data/remote/RestService.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.data.remote; 2 | 3 | import java.util.List; 4 | 5 | import be.neodigi.androidboilerplate.data.model.User; 6 | import retrofit2.http.GET; 7 | import rx.Observable; 8 | 9 | public interface RestService { 10 | 11 | @GET("users") 12 | Observable> getUsers(); 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/ActivityContext.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Qualifier; 7 | 8 | @Qualifier 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ActivityContext { 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/ApplicationContext.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Qualifier; 7 | 8 | @Qualifier 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ApplicationContext { 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/ConfigPersistent.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Scope; 7 | 8 | import be.neodigi.androidboilerplate.injection.component.ConfigPersistentComponent; 9 | 10 | /** 11 | * A scoping annotation to permit dependencies conform to the life of the 12 | * {@link ConfigPersistentComponent} 13 | */ 14 | @Scope 15 | @Retention(RetentionPolicy.RUNTIME) 16 | public @interface ConfigPersistent { 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/component/ActivityComponent.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.component; 2 | 3 | import be.neodigi.androidboilerplate.injection.scope.PerActivity; 4 | import be.neodigi.androidboilerplate.injection.module.ActivityModule; 5 | import be.neodigi.androidboilerplate.ui.main.MainActivity; 6 | import dagger.Subcomponent; 7 | 8 | /** 9 | * This component inject dependencies to all Activities across the application 10 | */ 11 | @PerActivity 12 | @Subcomponent(modules = ActivityModule.class) 13 | public interface ActivityComponent { 14 | 15 | void inject(MainActivity mainActivity); 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/component/ApplicationComponent.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.component; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import javax.inject.Singleton; 7 | 8 | import be.neodigi.androidboilerplate.data.DataManager; 9 | import be.neodigi.androidboilerplate.data.SyncService; 10 | import be.neodigi.androidboilerplate.data.local.DatabaseHelper; 11 | import be.neodigi.androidboilerplate.data.local.PreferencesHelper; 12 | import be.neodigi.androidboilerplate.data.remote.RestService; 13 | import be.neodigi.androidboilerplate.injection.ApplicationContext; 14 | import be.neodigi.androidboilerplate.injection.module.ApplicationModule; 15 | import be.neodigi.androidboilerplate.injection.module.RestModule; 16 | import be.neodigi.androidboilerplate.util.RxEventBus; 17 | import dagger.Component; 18 | import io.realm.Realm; 19 | 20 | @Singleton 21 | @Component(modules = {ApplicationModule.class, RestModule.class}) 22 | public interface ApplicationComponent { 23 | 24 | void inject(SyncService syncService); 25 | 26 | @ApplicationContext Context context(); 27 | Application application(); 28 | RestService restService(); 29 | PreferencesHelper preferencesHelper(); 30 | DatabaseHelper databaseHelper(); 31 | Realm realm(); 32 | DataManager dataManager(); 33 | RxEventBus eventBus(); 34 | } 35 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/component/ConfigPersistentComponent.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.component; 2 | 3 | import be.neodigi.androidboilerplate.injection.ConfigPersistent; 4 | import be.neodigi.androidboilerplate.injection.module.ActivityModule; 5 | import be.neodigi.androidboilerplate.ui.base.BaseActivity; 6 | import dagger.Component; 7 | 8 | /** 9 | * A dagger component that will live during the lifecycle of an Activity but it won't 10 | * be destroy during configuration changes. Check {@link BaseActivity} to see how this components 11 | * survives configuration changes. 12 | * Use the {@link ConfigPersistent} scope to annotate dependencies that need to survive 13 | * configuration changes (for example Presenters). 14 | */ 15 | @ConfigPersistent 16 | @Component(dependencies = ApplicationComponent.class) 17 | public interface ConfigPersistentComponent { 18 | 19 | ActivityComponent activityComponent(ActivityModule activityModule); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/module/ActivityModule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.module; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | 6 | import be.neodigi.androidboilerplate.injection.ActivityContext; 7 | import dagger.Module; 8 | import dagger.Provides; 9 | 10 | @Module 11 | public class ActivityModule { 12 | 13 | private Activity mActivity; 14 | 15 | public ActivityModule(Activity activity) { 16 | mActivity = activity; 17 | } 18 | 19 | @Provides 20 | Activity provideActivity() { 21 | return mActivity; 22 | } 23 | 24 | @Provides 25 | @ActivityContext 26 | Context providesContext() { 27 | return mActivity; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/module/ApplicationModule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.module; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import javax.inject.Singleton; 7 | 8 | import be.neodigi.androidboilerplate.injection.ApplicationContext; 9 | import dagger.Module; 10 | import dagger.Provides; 11 | import io.realm.Realm; 12 | import io.realm.RealmConfiguration; 13 | 14 | /** 15 | * Provide application-level dependencies. 16 | */ 17 | @Module 18 | public class ApplicationModule { 19 | private final Application mApplication; 20 | 21 | public ApplicationModule(Application application) { 22 | mApplication = application; 23 | } 24 | 25 | @Provides 26 | Application provideApplication() { 27 | return mApplication; 28 | } 29 | 30 | @Provides 31 | @ApplicationContext 32 | Context provideContext() { 33 | return mApplication; 34 | } 35 | 36 | @Provides 37 | @Singleton 38 | RealmConfiguration provideRealmConfiguration(@ApplicationContext Context context) { 39 | Realm.init(context); 40 | RealmConfiguration.Builder builder = new RealmConfiguration.Builder(); 41 | builder.name("boilerplate.realm"); 42 | return builder.build(); 43 | } 44 | 45 | @Provides 46 | Realm provideRealm(RealmConfiguration realmConfiguration) { 47 | return Realm.getInstance(realmConfiguration); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/module/RestModule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.module; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | 6 | import javax.inject.Singleton; 7 | 8 | import be.neodigi.androidboilerplate.BuildConfig; 9 | import be.neodigi.androidboilerplate.data.remote.RestService; 10 | import dagger.Module; 11 | import dagger.Provides; 12 | import okhttp3.OkHttpClient; 13 | import okhttp3.logging.HttpLoggingInterceptor; 14 | import retrofit2.Retrofit; 15 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; 16 | import retrofit2.converter.gson.GsonConverterFactory; 17 | import rx.schedulers.Schedulers; 18 | 19 | @Module 20 | public class RestModule { 21 | 22 | @Provides 23 | @Singleton 24 | Gson provideGson() { 25 | return new GsonBuilder() 26 | .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") 27 | .create(); 28 | } 29 | 30 | @Provides 31 | @Singleton 32 | OkHttpClient provideOkHttpClient() { 33 | return new OkHttpClient(); 34 | } 35 | 36 | @Provides 37 | @Singleton 38 | RestService provideRestService(Gson gson, OkHttpClient okHttpClient) { 39 | OkHttpClient.Builder httpClientBuilder = okHttpClient.newBuilder(); 40 | 41 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 42 | logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY 43 | : HttpLoggingInterceptor.Level.NONE); 44 | httpClientBuilder.addInterceptor(logging).build(); 45 | 46 | return new Retrofit.Builder() 47 | .baseUrl(BuildConfig.URL_ENDPOINT) 48 | .addConverterFactory(GsonConverterFactory.create(gson)) 49 | .addCallAdapterFactory(RxJavaCallAdapterFactory 50 | .createWithScheduler(Schedulers.io())) 51 | .callFactory(httpClientBuilder.build()) 52 | .build().create(RestService.class); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/injection/scope/PerActivity.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.injection.scope; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Scope; 7 | 8 | /** 9 | * A scoping annotation to permit objects whose lifetime should 10 | * conform to the life of the Activity to be memorised in the 11 | * correct component. 12 | */ 13 | @Scope 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface PerActivity { 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/base/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.base; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.util.LongSparseArray; 5 | import android.support.v7.app.AppCompatActivity; 6 | 7 | import java.util.concurrent.atomic.AtomicLong; 8 | 9 | import be.neodigi.androidboilerplate.BoilerplateApplication; 10 | import be.neodigi.androidboilerplate.injection.component.ActivityComponent; 11 | import be.neodigi.androidboilerplate.injection.component.ConfigPersistentComponent; 12 | import be.neodigi.androidboilerplate.injection.component.DaggerConfigPersistentComponent; 13 | import be.neodigi.androidboilerplate.injection.module.ActivityModule; 14 | import timber.log.Timber; 15 | 16 | public class BaseActivity extends AppCompatActivity { 17 | 18 | private static final String KEY_ACTIVITY_ID = "KEY_ACTIVITY_ID"; 19 | private static final AtomicLong NEXT_ID = new AtomicLong(0); 20 | private static final LongSparseArray sComponentsMap = new LongSparseArray<>(); 21 | 22 | private ActivityComponent mActivityComponent; 23 | private long mActivityId; 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | 29 | // Create the ActivityComponent and reuses cached ConfigPersistentComponent if this is 30 | // being called after a configuration change. 31 | mActivityId = savedInstanceState != null ? 32 | savedInstanceState.getLong(KEY_ACTIVITY_ID) : NEXT_ID.getAndIncrement(); 33 | ConfigPersistentComponent configPersistentComponent; 34 | if (null == sComponentsMap.get(mActivityId)) { 35 | Timber.i("Creating new ConfigPersistentComponent id=%d", mActivityId); 36 | configPersistentComponent = DaggerConfigPersistentComponent.builder() 37 | .applicationComponent(BoilerplateApplication.get(this).getComponent()) 38 | .build(); 39 | sComponentsMap.put(mActivityId, configPersistentComponent); 40 | } else { 41 | Timber.i("Reusing ConfigPersistentComponent id=%d", mActivityId); 42 | configPersistentComponent = sComponentsMap.get(mActivityId); 43 | } 44 | mActivityComponent = configPersistentComponent.activityComponent(new ActivityModule(this)); 45 | } 46 | 47 | @Override 48 | protected void onSaveInstanceState(Bundle outState) { 49 | super.onSaveInstanceState(outState); 50 | outState.putLong(KEY_ACTIVITY_ID, mActivityId); 51 | } 52 | 53 | @Override 54 | protected void onDestroy() { 55 | if (!isChangingConfigurations()) { 56 | Timber.i("Clearing ConfigPersistentComponent id=%d", mActivityId); 57 | sComponentsMap.remove(mActivityId); 58 | } 59 | super.onDestroy(); 60 | } 61 | 62 | public ActivityComponent activityComponent() { 63 | return mActivityComponent; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/base/BasePresenter.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.base; 2 | 3 | /** 4 | * Base class that implements the Presenter interface and provides a base implementation for 5 | * attachView() and detachView(). It also handles keeping a reference to the mvpView that 6 | * can be accessed from the children classes by calling getMvpView(). 7 | */ 8 | public class BasePresenter implements Presenter { 9 | 10 | private T mMvpView; 11 | 12 | @Override 13 | public void attachView(T mvpView) { 14 | mMvpView = mvpView; 15 | } 16 | 17 | @Override 18 | public void detachView() { 19 | mMvpView = null; 20 | } 21 | 22 | public boolean isViewAttached() { 23 | return mMvpView != null; 24 | } 25 | 26 | public T getMvpView() { 27 | return mMvpView; 28 | } 29 | 30 | public void checkViewAttached() { 31 | if (!isViewAttached()) throw new MvpViewNotAttachedException(); 32 | } 33 | 34 | public static class MvpViewNotAttachedException extends RuntimeException { 35 | public MvpViewNotAttachedException() { 36 | super("Please call Presenter.attachView(MvpView) before" + 37 | " requesting data to the Presenter"); 38 | } 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/base/MvpView.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.base; 2 | 3 | 4 | /** 5 | * Base interface that any class that wants to act as a View in the MVP (Model View Presenter) 6 | * pattern must implement. Generally this interface will be extended by a more specific interface 7 | * that then usually will be implemented by an Activity or Fragment. 8 | */ 9 | public interface MvpView { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/base/Presenter.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.base; 2 | 3 | /** 4 | * Every presenter in the app must either implement this interface or extend BasePresenter 5 | * indicating the MvpView type that wants to be attached with. 6 | */ 7 | public interface Presenter { 8 | 9 | void attachView(V mvpView); 10 | 11 | void detachView(); 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/main/MainActivity.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.main; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.widget.Toast; 9 | 10 | import java.util.Collections; 11 | import java.util.List; 12 | 13 | import javax.inject.Inject; 14 | 15 | import be.neodigi.androidboilerplate.R; 16 | import be.neodigi.androidboilerplate.data.SyncService; 17 | import be.neodigi.androidboilerplate.data.model.User; 18 | import be.neodigi.androidboilerplate.ui.base.BaseActivity; 19 | import be.neodigi.androidboilerplate.util.DialogFactory; 20 | import butterknife.BindView; 21 | import butterknife.ButterKnife; 22 | 23 | public class MainActivity extends BaseActivity implements MainMvpView { 24 | 25 | private static final String EXTRA_TRIGGER_SYNC_FLAG = 26 | "be.neodigi.androidboilerplate.ui.main.MainActivity.EXTRA_TRIGGER_SYNC_FLAG"; 27 | 28 | @Inject MainPresenter mMainPresenter; 29 | @Inject UsersAdapter mUsersAdapter; 30 | 31 | @BindView(R.id.recycler_view) RecyclerView mRecyclerView; 32 | 33 | /** 34 | * Return an Intent to start this Activity. 35 | * triggerDataSyncOnCreate allows disabling the background sync service onCreate. Should 36 | * only be set to false during testing. 37 | */ 38 | public static Intent getStartIntent(Context context, boolean triggerDataSyncOnCreate) { 39 | Intent intent = new Intent(context, MainActivity.class); 40 | intent.putExtra(EXTRA_TRIGGER_SYNC_FLAG, triggerDataSyncOnCreate); 41 | return intent; 42 | } 43 | 44 | @Override 45 | protected void onCreate(Bundle savedInstanceState) { 46 | super.onCreate(savedInstanceState); 47 | activityComponent().inject(this); 48 | setContentView(R.layout.activity_main); 49 | ButterKnife.bind(this); 50 | 51 | mRecyclerView.setAdapter(mUsersAdapter); 52 | mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 53 | mMainPresenter.attachView(this); 54 | mMainPresenter.loadUsers(); 55 | 56 | if (getIntent().getBooleanExtra(EXTRA_TRIGGER_SYNC_FLAG, true)) { 57 | startService(SyncService.getStartIntent(this)); 58 | } 59 | } 60 | 61 | @Override 62 | protected void onDestroy() { 63 | mMainPresenter.detachView(); 64 | super.onDestroy(); 65 | } 66 | 67 | /***** MVP View methods implementation *****/ 68 | 69 | @Override 70 | public void showUsers(List users) { 71 | mUsersAdapter.setUsers(users); 72 | mUsersAdapter.notifyDataSetChanged(); 73 | } 74 | 75 | @Override 76 | public void showError() { 77 | DialogFactory.createGenericErrorDialog(this, getString(R.string.error_loading_ribots)) 78 | .show(); 79 | } 80 | 81 | @Override 82 | public void showUsersEmpty() { 83 | mUsersAdapter.setUsers(Collections.emptyList()); 84 | mUsersAdapter.notifyDataSetChanged(); 85 | Toast.makeText(this, R.string.empty_ribots, Toast.LENGTH_LONG).show(); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/main/MainMvpView.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.main; 2 | 3 | import java.util.List; 4 | 5 | import be.neodigi.androidboilerplate.data.model.User; 6 | import be.neodigi.androidboilerplate.ui.base.MvpView; 7 | 8 | public interface MainMvpView extends MvpView { 9 | 10 | void showUsers(List users); 11 | 12 | void showUsersEmpty(); 13 | 14 | void showError(); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/main/MainPresenter.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.main; 2 | 3 | import java.util.List; 4 | 5 | import javax.inject.Inject; 6 | 7 | import be.neodigi.androidboilerplate.data.DataManager; 8 | import be.neodigi.androidboilerplate.data.model.User; 9 | import be.neodigi.androidboilerplate.injection.ConfigPersistent; 10 | import be.neodigi.androidboilerplate.ui.base.BasePresenter; 11 | import be.neodigi.androidboilerplate.util.RxUtil; 12 | import rx.Subscriber; 13 | import rx.Subscription; 14 | import rx.android.schedulers.AndroidSchedulers; 15 | import timber.log.Timber; 16 | 17 | @ConfigPersistent 18 | public class MainPresenter extends BasePresenter { 19 | 20 | private final DataManager mDataManager; 21 | private Subscription mSubscription; 22 | 23 | @Inject 24 | public MainPresenter(DataManager dataManager) { 25 | mDataManager = dataManager; 26 | } 27 | 28 | @Override 29 | public void attachView(MainMvpView mvpView) { 30 | super.attachView(mvpView); 31 | } 32 | 33 | @Override 34 | public void detachView() { 35 | super.detachView(); 36 | if (mSubscription != null) mSubscription.unsubscribe(); 37 | } 38 | 39 | public void loadUsers() { 40 | checkViewAttached(); 41 | RxUtil.unsubscribe(mSubscription); 42 | mSubscription = mDataManager.getUsers() 43 | .observeOn(AndroidSchedulers.mainThread()) 44 | .subscribe(new Subscriber>() { 45 | @Override 46 | public void onCompleted() { 47 | } 48 | 49 | @Override 50 | public void onError(Throwable e) { 51 | Timber.e(e, "There was an error loading the users."); 52 | getMvpView().showError(); 53 | } 54 | 55 | @Override 56 | public void onNext(List users) { 57 | if (users.isEmpty()) { 58 | getMvpView().showUsersEmpty(); 59 | } else { 60 | getMvpView().showUsers(users); 61 | } 62 | } 63 | }); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/ui/main/UsersAdapter.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.ui.main; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.TextView; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import javax.inject.Inject; 13 | 14 | import be.neodigi.androidboilerplate.R; 15 | import be.neodigi.androidboilerplate.data.model.User; 16 | import butterknife.BindView; 17 | import butterknife.ButterKnife; 18 | 19 | public class UsersAdapter extends RecyclerView.Adapter { 20 | 21 | private List mUsers; 22 | 23 | @Inject 24 | public UsersAdapter() { 25 | mUsers = new ArrayList<>(); 26 | } 27 | 28 | public void setUsers(List users) { 29 | mUsers = users; 30 | } 31 | 32 | @Override 33 | public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 34 | View itemView = LayoutInflater.from(parent.getContext()) 35 | .inflate(R.layout.item_ribot, parent, false); 36 | return new UserViewHolder(itemView); 37 | } 38 | 39 | @Override 40 | public void onBindViewHolder(UserViewHolder holder, int position) { 41 | User user = mUsers.get(position); 42 | holder.nameTextView.setText(String.format("%s %s", 43 | user.getUsername(), user.getName())); 44 | holder.emailTextView.setText(user.getEmail()); 45 | } 46 | 47 | @Override 48 | public int getItemCount() { 49 | return mUsers.size(); 50 | } 51 | 52 | class UserViewHolder extends RecyclerView.ViewHolder { 53 | 54 | @BindView(R.id.text_name) TextView nameTextView; 55 | @BindView(R.id.text_email) TextView emailTextView; 56 | 57 | public UserViewHolder(View itemView) { 58 | super(itemView); 59 | ButterKnife.bind(this, itemView); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/AndroidComponentUtil.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import android.app.ActivityManager; 4 | import android.app.ActivityManager.RunningServiceInfo; 5 | import android.content.ComponentName; 6 | import android.content.Context; 7 | import android.content.pm.PackageManager; 8 | 9 | public final class AndroidComponentUtil { 10 | 11 | public static void toggleComponent(Context context, Class componentClass, boolean enable) { 12 | ComponentName componentName = new ComponentName(context, componentClass); 13 | PackageManager pm = context.getPackageManager(); 14 | pm.setComponentEnabledSetting(componentName, 15 | enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : 16 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 17 | PackageManager.DONT_KILL_APP); 18 | } 19 | 20 | public static boolean isServiceRunning(Context context, Class serviceClass) { 21 | ActivityManager manager = 22 | (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 23 | for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 24 | if (serviceClass.getName().equals(service.service.getClassName())) { 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/DialogFactory.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import android.app.Dialog; 4 | import android.app.ProgressDialog; 5 | import android.content.Context; 6 | import android.support.annotation.StringRes; 7 | import android.support.v7.app.AlertDialog; 8 | 9 | import be.neodigi.androidboilerplate.R; 10 | 11 | public final class DialogFactory { 12 | 13 | public static Dialog createSimpleOkErrorDialog(Context context, String title, String message) { 14 | AlertDialog.Builder alertDialog = new AlertDialog.Builder(context) 15 | .setTitle(title) 16 | .setMessage(message) 17 | .setNeutralButton(R.string.dialog_action_ok, null); 18 | return alertDialog.create(); 19 | } 20 | 21 | public static Dialog createSimpleOkErrorDialog(Context context, 22 | @StringRes int titleResource, 23 | @StringRes int messageResource) { 24 | 25 | return createSimpleOkErrorDialog(context, 26 | context.getString(titleResource), 27 | context.getString(messageResource)); 28 | } 29 | 30 | public static Dialog createGenericErrorDialog(Context context, String message) { 31 | AlertDialog.Builder alertDialog = new AlertDialog.Builder(context) 32 | .setTitle(context.getString(R.string.dialog_error_title)) 33 | .setMessage(message) 34 | .setNeutralButton(R.string.dialog_action_ok, null); 35 | return alertDialog.create(); 36 | } 37 | 38 | public static Dialog createGenericErrorDialog(Context context, @StringRes int messageResource) { 39 | return createGenericErrorDialog(context, context.getString(messageResource)); 40 | } 41 | 42 | public static ProgressDialog createProgressDialog(Context context, String message) { 43 | ProgressDialog progressDialog = new ProgressDialog(context); 44 | progressDialog.setMessage(message); 45 | return progressDialog; 46 | } 47 | 48 | public static ProgressDialog createProgressDialog(Context context, 49 | @StringRes int messageResource) { 50 | return createProgressDialog(context, context.getString(messageResource)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/NetworkUtil.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | 7 | import retrofit2.adapter.rxjava.HttpException; 8 | 9 | public class NetworkUtil { 10 | 11 | /** 12 | * Returns true if the Throwable is an instance of RetrofitError with an 13 | * http status code equals to the given one. 14 | */ 15 | public static boolean isHttpStatusCode(Throwable throwable, int statusCode) { 16 | return throwable instanceof HttpException 17 | && ((HttpException) throwable).code() == statusCode; 18 | } 19 | 20 | public static boolean isNetworkConnected(Context context) { 21 | ConnectivityManager cm = 22 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 23 | NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 24 | return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/RxEventBus.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import javax.inject.Inject; 4 | import javax.inject.Singleton; 5 | 6 | import rx.Observable; 7 | import rx.functions.Func1; 8 | import rx.subjects.PublishSubject; 9 | 10 | /** 11 | * A simple event bus built with RxJava 12 | */ 13 | @Singleton 14 | public class RxEventBus { 15 | 16 | private final PublishSubject mBusSubject; 17 | 18 | @Inject 19 | public RxEventBus() { 20 | mBusSubject = PublishSubject.create(); 21 | } 22 | 23 | /** 24 | * Posts an object (usually an Event) to the bus 25 | */ 26 | public void post(Object event) { 27 | mBusSubject.onNext(event); 28 | } 29 | 30 | /** 31 | * Observable that will emmit everything posted to the event bus. 32 | */ 33 | public Observable observable() { 34 | return mBusSubject; 35 | } 36 | 37 | /** 38 | * Observable that only emits events of a specific class. 39 | * Use this if you only want to subscribe to one type of events. 40 | */ 41 | public Observable filteredObservable(final Class eventClass) { 42 | return mBusSubject.filter(new Func1() { 43 | @Override 44 | public Boolean call(Object event) { 45 | return eventClass.isInstance(event); 46 | } 47 | }).map(new Func1() { 48 | //Safe to cast because of the previous filter 49 | @SuppressWarnings("unchecked") 50 | @Override 51 | public T call(Object event) { 52 | return (T) event; 53 | } 54 | }); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/RxUtil.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import rx.Subscription; 4 | 5 | public class RxUtil { 6 | 7 | public static void unsubscribe(Subscription subscription) { 8 | if (subscription != null && !subscription.isUnsubscribed()) { 9 | subscription.unsubscribe(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /app/src/main/java/be/neodigi/androidboilerplate/util/ViewUtil.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.res.Resources; 6 | import android.view.inputmethod.InputMethodManager; 7 | 8 | public final class ViewUtil { 9 | 10 | public static float pxToDp(float px) { 11 | float densityDpi = Resources.getSystem().getDisplayMetrics().densityDpi; 12 | return px / (densityDpi / 160f); 13 | } 14 | 15 | public static int dpToPx(int dp) { 16 | float density = Resources.getSystem().getDisplayMetrics().density; 17 | return Math.round(dp * density); 18 | } 19 | 20 | public static void hideKeyboard(Activity activity) { 21 | InputMethodManager imm = 22 | (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); 23 | imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_ribot.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 18 | 19 | 25 | 26 | 33 | 34 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #222222 4 | #000000 5 | #FFFFFF 6 | #ffdfdfdf 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | 24sp 7 | 22sp 8 | 20sp 9 | 18sp 10 | 16sp 11 | 14sp 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidBoilerPlate 3 | 4 | Settings 5 | 6 | OK 7 | Cancel 8 | Sorry 9 | 10 | There aren\'t any users 11 | There was a problem loading the users 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/DataManagerTest.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.mockito.Mock; 7 | import org.mockito.runners.MockitoJUnitRunner; 8 | 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | import be.neodigi.androidboilerplate.data.DataManager; 13 | import be.neodigi.androidboilerplate.data.local.DatabaseHelper; 14 | import be.neodigi.androidboilerplate.data.local.PreferencesHelper; 15 | import be.neodigi.androidboilerplate.data.model.User; 16 | import be.neodigi.androidboilerplate.data.remote.RestService; 17 | import be.neodigi.androidboilerplate.test.common.TestDataFactory; 18 | import rx.Observable; 19 | import rx.observers.TestSubscriber; 20 | 21 | import static org.mockito.Matchers.anyListOf; 22 | import static org.mockito.Mockito.never; 23 | import static org.mockito.Mockito.verify; 24 | import static org.mockito.Mockito.when; 25 | 26 | /** 27 | * This test class performs local unit tests without dependencies on the Android framework 28 | * For testing methods in the DataManager follow this approach: 29 | * 1. Stub mock helper classes that your method relies on. e.g. RetrofitServices or DatabaseHelper 30 | * 2. Test the Observable using TestSubscriber 31 | * 3. Optionally write a SEPARATE test that verifies that your method is calling the right helper 32 | * using Mockito.verify() 33 | */ 34 | @RunWith(MockitoJUnitRunner.class) 35 | public class DataManagerTest { 36 | 37 | @Mock DatabaseHelper mMockDatabaseHelper; 38 | @Mock PreferencesHelper mMockPreferencesHelper; 39 | @Mock RestService mMockRestService; 40 | private DataManager mDataManager; 41 | 42 | @Before 43 | public void setUp() { 44 | mDataManager = new DataManager(mMockRestService, mMockPreferencesHelper, 45 | mMockDatabaseHelper); 46 | } 47 | 48 | @Test 49 | public void syncUsersEmitsValues() { 50 | List users = Arrays.asList(TestDataFactory.makeUser("r1"), 51 | TestDataFactory.makeUser("r2")); 52 | stubSyncUsersHelperCalls(users); 53 | 54 | TestSubscriber result = new TestSubscriber<>(); 55 | mDataManager.syncUsers().subscribe(result); 56 | result.assertNoErrors(); 57 | result.assertReceivedOnNext(users); 58 | } 59 | 60 | @Test 61 | public void syncUsersCallsApiAndDatabase() { 62 | List users = Arrays.asList(TestDataFactory.makeUser("r1"), 63 | TestDataFactory.makeUser("r2")); 64 | stubSyncUsersHelperCalls(users); 65 | 66 | mDataManager.syncUsers().subscribe(); 67 | // Verify right calls to helper methods 68 | verify(mMockRestService).getUsers(); 69 | verify(mMockDatabaseHelper).setUsers(users); 70 | } 71 | 72 | @Test 73 | public void syncUsersDoesNotCallDatabaseWhenApiFails() { 74 | when(mMockRestService.getUsers()) 75 | .thenReturn(Observable.>error(new RuntimeException())); 76 | 77 | mDataManager.syncUsers().subscribe(new TestSubscriber()); 78 | // Verify right calls to helper methods 79 | verify(mMockRestService).getUsers(); 80 | verify(mMockDatabaseHelper, never()).setUsers(anyListOf(User.class)); 81 | } 82 | 83 | private void stubSyncUsersHelperCalls(List users) { 84 | // Stub calls to the rest service and database helper. 85 | when(mMockRestService.getUsers()) 86 | .thenReturn(Observable.just(users)); 87 | when(mMockDatabaseHelper.setUsers(users)) 88 | .thenReturn(Observable.from(users)); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/DatabaseHelperTest.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate; 2 | 3 | import org.junit.Before; 4 | import org.junit.Rule; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.powermock.api.mockito.PowerMockito; 8 | import org.powermock.core.classloader.annotations.PowerMockIgnore; 9 | import org.powermock.core.classloader.annotations.PrepareForTest; 10 | import org.powermock.modules.junit4.rule.PowerMockRule; 11 | import org.robolectric.RobolectricGradleTestRunner; 12 | import org.robolectric.annotation.Config; 13 | 14 | import be.neodigi.androidboilerplate.data.model.User; 15 | import io.realm.Realm; 16 | 17 | import static org.hamcrest.CoreMatchers.is; 18 | import static org.junit.Assert.assertThat; 19 | import static org.mockito.Mockito.when; 20 | import static org.powermock.api.mockito.PowerMockito.mockStatic; 21 | 22 | /** 23 | * Unit tests integration with Realm using Robolectric 24 | */ 25 | 26 | @RunWith(RobolectricGradleTestRunner.class) 27 | @Config(constants = BuildConfig.class, sdk = 19) 28 | @PowerMockIgnore({"org.mockito.*"}) 29 | @PrepareForTest({Realm.class}) 30 | public class DatabaseHelperTest { 31 | 32 | @Rule 33 | public PowerMockRule rule = new PowerMockRule(); 34 | private Realm mMockRealm; 35 | 36 | @Before 37 | public void setupRealm() { 38 | mockStatic(Realm.class); 39 | 40 | Realm mockRealm = PowerMockito.mock(Realm.class); 41 | 42 | when(Realm.getDefaultInstance()).thenReturn(mockRealm); 43 | 44 | mMockRealm = mockRealm; 45 | } 46 | 47 | @Test 48 | public void shouldBeAbleToGetDefaultInstance() { 49 | assertThat(Realm.getDefaultInstance(), is(mMockRealm)); 50 | } 51 | 52 | @Test 53 | public void shouldBeAbleToMockRealmMethods() { 54 | when(mMockRealm.isAutoRefresh()).thenReturn(true); 55 | assertThat(mMockRealm.isAutoRefresh(), is(true)); 56 | 57 | when(mMockRealm.isAutoRefresh()).thenReturn(false); 58 | assertThat(mMockRealm.isAutoRefresh(), is(false)); 59 | } 60 | 61 | @Test 62 | public void shouldBeAbleToCreateRealmObject() { 63 | User user = new User(); 64 | when(mMockRealm.createObject(User.class)).thenReturn(user); 65 | 66 | User output = mMockRealm.createObject(User.class); 67 | 68 | assertThat(output, is(user)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/MainPresenterTest.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.mockito.Mock; 9 | import org.mockito.runners.MockitoJUnitRunner; 10 | 11 | import java.util.Collections; 12 | import java.util.List; 13 | 14 | import be.neodigi.androidboilerplate.data.DataManager; 15 | import be.neodigi.androidboilerplate.data.model.User; 16 | import be.neodigi.androidboilerplate.test.common.TestDataFactory; 17 | import be.neodigi.androidboilerplate.ui.main.MainMvpView; 18 | import be.neodigi.androidboilerplate.ui.main.MainPresenter; 19 | import be.neodigi.androidboilerplate.util.RxSchedulersOverrideRule; 20 | import rx.Observable; 21 | 22 | import static org.mockito.Matchers.anyListOf; 23 | import static org.mockito.Mockito.doReturn; 24 | import static org.mockito.Mockito.never; 25 | import static org.mockito.Mockito.verify; 26 | 27 | @RunWith(MockitoJUnitRunner.class) 28 | public class MainPresenterTest { 29 | 30 | @Mock MainMvpView mMockMainMvpView; 31 | @Mock DataManager mMockDataManager; 32 | private MainPresenter mMainPresenter; 33 | 34 | @Rule 35 | public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); 36 | 37 | @Before 38 | public void setUp() { 39 | mMainPresenter = new MainPresenter(mMockDataManager); 40 | mMainPresenter.attachView(mMockMainMvpView); 41 | } 42 | 43 | @After 44 | public void tearDown() { 45 | mMainPresenter.detachView(); 46 | } 47 | 48 | @Test 49 | public void loadUsersReturnsUsers() { 50 | List users = TestDataFactory.makeListUsers(10); 51 | doReturn(Observable.just(users)) 52 | .when(mMockDataManager) 53 | .getUsers(); 54 | 55 | mMainPresenter.loadUsers(); 56 | verify(mMockMainMvpView).showUsers(users); 57 | verify(mMockMainMvpView, never()).showUsersEmpty(); 58 | verify(mMockMainMvpView, never()).showError(); 59 | } 60 | 61 | @Test 62 | public void loadUsersReturnsEmptyList() { 63 | doReturn(Observable.just(Collections.emptyList())) 64 | .when(mMockDataManager) 65 | .getUsers(); 66 | 67 | mMainPresenter.loadUsers(); 68 | verify(mMockMainMvpView).showUsersEmpty(); 69 | verify(mMockMainMvpView, never()).showUsers(anyListOf(User.class)); 70 | verify(mMockMainMvpView, never()).showError(); 71 | } 72 | 73 | @Test 74 | public void loadUsersFails() { 75 | doReturn(Observable.error(new RuntimeException())) 76 | .when(mMockDataManager) 77 | .getUsers(); 78 | 79 | mMainPresenter.loadUsers(); 80 | verify(mMockMainMvpView).showError(); 81 | verify(mMockMainMvpView, never()).showUsersEmpty(); 82 | verify(mMockMainMvpView, never()).showUsers(anyListOf(User.class)); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/util/DefaultConfig.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | /** 4 | * Robolectric default config properties 5 | */ 6 | public class DefaultConfig { 7 | //The api level that Roboelectric will use to run the unit tests 8 | public static final int EMULATE_SDK = 23; 9 | } -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/util/RxEventBusTest.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import org.junit.Before; 4 | import org.junit.Rule; 5 | import org.junit.Test; 6 | 7 | import rx.observers.TestSubscriber; 8 | 9 | public class RxEventBusTest { 10 | 11 | private RxEventBus mEventBus; 12 | 13 | @Rule 14 | // Must be added to every test class that targets app code that uses RxJava 15 | public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); 16 | 17 | @Before 18 | public void setUp() { 19 | mEventBus = new RxEventBus(); 20 | } 21 | 22 | @Test 23 | public void postedObjectsAreReceived() { 24 | TestSubscriber testSubscriber = new TestSubscriber<>(); 25 | mEventBus.observable().subscribe(testSubscriber); 26 | 27 | Object event1 = new Object(); 28 | Object event2 = new Object(); 29 | mEventBus.post(event1); 30 | mEventBus.post(event2); 31 | 32 | testSubscriber.assertValues(event1, event2); 33 | } 34 | 35 | @Test 36 | public void filteredObservableOnlyReceivesSomeObjects() { 37 | TestSubscriber testSubscriber = new TestSubscriber<>(); 38 | mEventBus.filteredObservable(String.class).subscribe(testSubscriber); 39 | 40 | String stringEvent = "Event"; 41 | Integer intEvent = 20; 42 | mEventBus.post(stringEvent); 43 | mEventBus.post(intEvent); 44 | 45 | testSubscriber.assertValueCount(1); 46 | testSubscriber.assertValue(stringEvent); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/src/test/java/be/neodigi/androidboilerplate/util/RxSchedulersOverrideRule.java: -------------------------------------------------------------------------------- 1 | package be.neodigi.androidboilerplate.util; 2 | 3 | import org.junit.rules.TestRule; 4 | import org.junit.runner.Description; 5 | import org.junit.runners.model.Statement; 6 | 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | 10 | import rx.Scheduler; 11 | import rx.android.plugins.RxAndroidPlugins; 12 | import rx.android.plugins.RxAndroidSchedulersHook; 13 | import rx.plugins.RxJavaPlugins; 14 | import rx.plugins.RxJavaSchedulersHook; 15 | import rx.schedulers.Schedulers; 16 | 17 | /** 18 | * This rule registers SchedulerHooks for RxJava and RxAndroid to ensure that subscriptions 19 | * always subscribeOn and observeOn Schedulers.immediate(). 20 | * Warning, this rule will reset RxAndroidPlugins and RxJavaPlugins before and after each test so 21 | * if the application code uses RxJava plugins this may affect the behaviour of the testing method. 22 | */ 23 | public class RxSchedulersOverrideRule implements TestRule { 24 | 25 | private final RxJavaSchedulersHook mRxJavaSchedulersHook = new RxJavaSchedulersHook() { 26 | @Override 27 | public Scheduler getIOScheduler() { 28 | return Schedulers.immediate(); 29 | } 30 | 31 | @Override 32 | public Scheduler getNewThreadScheduler() { 33 | return Schedulers.immediate(); 34 | } 35 | }; 36 | 37 | private final RxAndroidSchedulersHook mRxAndroidSchedulersHook = new RxAndroidSchedulersHook() { 38 | @Override 39 | public Scheduler getMainThreadScheduler() { 40 | return Schedulers.immediate(); 41 | } 42 | }; 43 | 44 | // Hack to get around RxJavaPlugins.reset() not being public 45 | // See https://github.com/ReactiveX/RxJava/issues/2297 46 | // Hopefully the method will be public in new releases of RxAndroid and we can remove the hack. 47 | private void callResetViaReflectionIn(RxJavaPlugins rxJavaPlugins) 48 | throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { 49 | Method method = rxJavaPlugins.getClass().getDeclaredMethod("reset"); 50 | method.setAccessible(true); 51 | method.invoke(rxJavaPlugins); 52 | } 53 | 54 | @Override 55 | public Statement apply(final Statement base, Description description) { 56 | return new Statement() { 57 | @Override 58 | public void evaluate() throws Throwable { 59 | RxAndroidPlugins.getInstance().reset(); 60 | RxAndroidPlugins.getInstance().registerSchedulersHook(mRxAndroidSchedulersHook); 61 | 62 | RxJavaPlugins.getInstance().reset(); 63 | RxJavaPlugins.getInstance().registerSchedulersHook(mRxJavaSchedulersHook); 64 | 65 | base.evaluate(); 66 | 67 | RxAndroidPlugins.getInstance().reset(); 68 | RxJavaPlugins.getInstance().reset(); 69 | } 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | maven { url 'https://maven.fabric.io/public' } 5 | } 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:2.2.0' 8 | classpath 'com.github.triplet.gradle:play-publisher:1.1.4' 9 | classpath 'io.realm:realm-gradle-plugin:2.0.0' 10 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 11 | //noinspection GradleDynamicVersion 12 | classpath 'io.fabric.tools:gradle:1.+' 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | jcenter() 19 | maven { url 'https://maven.fabric.io/public' } 20 | } 21 | } 22 | 23 | task wrapper(type: Wrapper) { 24 | gradleVersion = '3.1' 25 | distributionUrl = distributionUrl.replace("bin", "all") 26 | } 27 | -------------------------------------------------------------------------------- /config/quality/checkstyle/checkstyle-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 77 | 79 | 81 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 92 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 117 | 118 | 119 | 120 | 121 | 123 | 124 | 125 | 126 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 137 | 138 | 139 | 140 | 141 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 151 | 152 | 153 | 154 | 155 | 157 | 158 | 159 | 160 | 161 | 163 | 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /config/quality/findbugs/android-exclude-filter.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /config/quality/pmd/pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Custom ruleset for user Android application 8 | 9 | .*/R.java 10 | .*/gen/.* 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /config/quality/quality.gradle: -------------------------------------------------------------------------------- 1 | /** 2 | * Set up Checkstyle, Findbugs and PMD to perform extensive code analysis. 3 | * 4 | * Gradle tasks added: 5 | * - checkstyle 6 | * - findbugs 7 | * - pmd 8 | * 9 | * The three tasks above are added as dependencies of the check task so running check will 10 | * run all of them. 11 | */ 12 | 13 | apply plugin: 'checkstyle' 14 | apply plugin: 'findbugs' 15 | apply plugin: 'pmd' 16 | 17 | dependencies { 18 | checkstyle 'com.puppycrawl.tools:checkstyle:6.5' 19 | } 20 | 21 | def qualityConfigDir = "$project.rootDir/config/quality"; 22 | def reportsDir = "$project.buildDir/reports" 23 | 24 | check.dependsOn 'checkstyle', 'findbugs', 'pmd' 25 | 26 | task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code style checks') { 27 | configFile file("$qualityConfigDir/checkstyle/checkstyle-config.xml") 28 | source 'src' 29 | include '**/*.java' 30 | 31 | reports { 32 | xml.enabled = true 33 | xml { 34 | destination "$reportsDir/checkstyle/checkstyle.xml" 35 | } 36 | } 37 | 38 | classpath = files( ) 39 | } 40 | 41 | task findbugs(type: FindBugs, 42 | group: 'Verification', 43 | description: 'Inspect java bytecode for bugs', 44 | dependsOn: ['compileDebugSources','compileReleaseSources']) { 45 | 46 | ignoreFailures = false 47 | effort = "max" 48 | reportLevel = "high" 49 | excludeFilter = new File("$qualityConfigDir/findbugs/android-exclude-filter.xml") 50 | classes = files("$project.rootDir/app/build/intermediates/classes") 51 | 52 | source 'src' 53 | include '**/*.java' 54 | exclude '**/gen/**' 55 | 56 | reports { 57 | xml.enabled = true 58 | html.enabled = false 59 | xml { 60 | destination "$reportsDir/findbugs/findbugs.xml" 61 | } 62 | html { 63 | destination "$reportsDir/findbugs/findbugs.html" 64 | } 65 | } 66 | 67 | classpath = files() 68 | } 69 | 70 | 71 | task pmd(type: Pmd, group: 'Verification', description: 'Inspect sourcecode for bugs') { 72 | ruleSetFiles = files("$qualityConfigDir/pmd/pmd-ruleset.xml") 73 | ignoreFailures = false 74 | ruleSets = [] 75 | 76 | source 'src' 77 | include '**/*.java' 78 | exclude '**/gen/**' 79 | 80 | reports { 81 | xml.enabled = true 82 | html.enabled = true 83 | xml { 84 | destination "$reportsDir/pmd/pmd.xml" 85 | } 86 | html { 87 | destination "$reportsDir/pmd/pmd.html" 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /crashlytics_release_notes.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/crashlytics_release_notes.txt -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | 2 | # Gradle performance variables 3 | org.gradle.jvmargs=-Xmx4G -XX:MaxPermSize=512m 4 | org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Sep 29 15:33:35 CEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-all.zip 7 | -------------------------------------------------------------------------------- /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 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /images/check-task-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NeoDigi/android-boilerplate/dc534b4db29fcfff893c6a10cdb5ea3c805e0d74/images/check-task-diagram.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------