├── .github └── workflows │ ├── apk_generate.yml │ ├── send_apk_appcenter.yml │ ├── send_apk_diawi.yml │ ├── send_apk_slack.yml │ ├── unit_tests.yml │ └── upload_apk_in_releases.yml ├── .gitignore ├── Android-GithubActions-App.apk ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── wajahatkarim3 │ │ └── imagine │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── wajahatkarim3 │ │ │ └── imagine │ │ │ ├── ImagineApp.kt │ │ │ ├── adapters │ │ │ ├── PhotosAdapter.kt │ │ │ └── TagsAdapter.kt │ │ │ ├── base │ │ │ ├── BaseActivity.kt │ │ │ └── BaseFragment.kt │ │ │ ├── data │ │ │ ├── DataResource.kt │ │ │ ├── DataState.kt │ │ │ ├── remote │ │ │ │ ├── ApiResponse.kt │ │ │ │ ├── ApiResponseCallAdapter.kt │ │ │ │ ├── ApiResponseCallAdapterFactory.kt │ │ │ │ ├── CoroutinesSuspensions.kt │ │ │ │ ├── ResponseTransformer.kt │ │ │ │ ├── UnsplashApiService.kt │ │ │ │ └── responses │ │ │ │ │ └── SearchPhotosResponse.kt │ │ │ ├── repository │ │ │ │ ├── ImagineRepository.kt │ │ │ │ └── ImagineRepositoryImpl.kt │ │ │ └── usecases │ │ │ │ ├── FetchPopularPhotosUsecase.kt │ │ │ │ └── SearchPhotosUsecase.kt │ │ │ ├── di │ │ │ ├── components │ │ │ │ └── AppComponent.kt │ │ │ ├── factories │ │ │ │ └── AppViewModelProviderFactory.kt │ │ │ └── modules │ │ │ │ ├── ActivityModule.kt │ │ │ │ ├── FragmentModule.kt │ │ │ │ ├── NetworkApiModule.kt │ │ │ │ ├── RepositoryModule.kt │ │ │ │ ├── ViewModelModule.kt │ │ │ │ └── ViewModelsFactoryModule.kt │ │ │ ├── model │ │ │ ├── PhotoModel.kt │ │ │ ├── PhotoUrlsModel.kt │ │ │ ├── TagModel.kt │ │ │ └── UserModel.kt │ │ │ ├── ui │ │ │ ├── MainActivity.kt │ │ │ ├── home │ │ │ │ ├── HomeFragment.kt │ │ │ │ ├── HomeUiState.kt │ │ │ │ └── HomeViewModel.kt │ │ │ └── photodetails │ │ │ │ ├── PhotoDetailsFragment.kt │ │ │ │ ├── PhotoDetailsUiState.kt │ │ │ │ └── PhotoDetailsViewModel.kt │ │ │ └── utils │ │ │ ├── AppConstants.kt │ │ │ ├── StringUtils.kt │ │ │ └── TheKtx.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ ├── ic_baseline_bedtime_24.xml │ │ ├── ic_baseline_search_24.xml │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── home_fragment.xml │ │ ├── photo_details_fragment.xml │ │ ├── photo_item_layout.xml │ │ └── tag_item_layout.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── navigation │ │ └── main_nav_graph.xml │ │ ├── values-night │ │ ├── colors.xml │ │ └── themes.xml │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ ├── test-common │ └── java │ │ └── MockTestUtil.kt │ └── test │ ├── java │ └── com │ │ └── wajahatkarim3 │ │ └── imagine │ │ ├── ExampleUnitTest.kt │ │ ├── MainCoroutinesRule.kt │ │ ├── data │ │ ├── remote │ │ │ ├── ApiResponseTest.kt │ │ │ ├── UnsplashApiServiceTest.kt │ │ │ └── api │ │ │ │ ├── ApiAbstract.kt │ │ │ │ └── ApiUtil.kt │ │ ├── repository │ │ │ └── ImagineRepositoryImplTest.kt │ │ └── usecases │ │ │ ├── FetchPopularPhotosUsecaseTest.kt │ │ │ └── SearchPhotosUsecaseTest.kt │ │ └── ui │ │ └── home │ │ └── HomeViewModelTest.kt │ └── resources │ └── api-response │ ├── photos_list_response.json │ └── search_photos_response.json ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshots ├── Imagine-UnitTests.PNG ├── PhotoDetailsDay.png ├── PhotoDetailsNight.png ├── PopularPhotosDay.png ├── PopularPhotosNight.png ├── SearchResultsDay.png └── SearchResultsNight.png └── settings.gradle /.github/workflows/apk_generate.yml: -------------------------------------------------------------------------------- 1 | name: Generate APK 2 | on: 3 | push: 4 | branches: [ main ] 5 | 6 | jobs: 7 | # Run Unit Tests etc before Generating APK here. 8 | # .... 9 | 10 | # A job to generate debug APK and upload on Github Artifacts 11 | apk: 12 | name: Generate APK 13 | runs-on: ubuntu-18.04 14 | 15 | steps: 16 | - uses: actions/checkout@v1 17 | - name: set up JDK 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: 11.0.3 21 | 22 | - name: Grant Permission to Execute 23 | run: chmod +x gradlew 24 | 25 | - name: Build debug APK 26 | run: bash ./gradlew assembleDebug --stacktrace 27 | 28 | - name: Upload APK to Github Artifacts 29 | uses: actions/upload-artifact@v1 30 | with: 31 | name: app 32 | path: app/build/outputs/apk/debug/app-debug.apk 33 | -------------------------------------------------------------------------------- /.github/workflows/send_apk_appcenter.yml: -------------------------------------------------------------------------------- 1 | name: Send APK to AppCenter 2 | on: 3 | push: 4 | branches: 5 | - 'main' 6 | 7 | jobs: 8 | 9 | apk: 10 | name: Send APK to AppCenter 11 | runs-on: ubuntu-18.04 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: set up JDK 1.8 16 | uses: actions/setup-java@v1 17 | with: 18 | java-version: 1.8 19 | 20 | - name: Grant Permission to Execute 21 | run: chmod +x gradlew 22 | 23 | - name: Build debug APK 24 | run: bash ./gradlew assembleDebug --stacktrace 25 | 26 | - name: Upload APK to Github Artifacts 27 | uses: actions/upload-artifact@v1 28 | with: 29 | name: app 30 | path: app/build/outputs/apk/debug/app-debug.apk 31 | 32 | 33 | - name: Distribute to AppCenter 34 | uses: wzieba/AppCenter-Github-Action@v1.3.2 35 | with: 36 | appName: wajahatkarim3/Actions-Demo 37 | token: ${{ secrets.APP_CENTER_TOKEN }} 38 | group: public 39 | file: app/build/outputs/apk/debug/app-debug.apk 40 | debug: false 41 | -------------------------------------------------------------------------------- /.github/workflows/send_apk_diawi.yml: -------------------------------------------------------------------------------- 1 | name: Send APK to Diawii 2 | on: 3 | push: 4 | branches: 5 | - 'main' 6 | 7 | jobs: 8 | 9 | apk: 10 | name: Send APK to Diawii 11 | runs-on: ubuntu-18.04 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: set up JDK 1.8 16 | uses: actions/setup-java@v1 17 | with: 18 | java-version: 1.8 19 | 20 | - name: Grant Permission to Execute 21 | run: chmod +x gradlew 22 | 23 | - name: Build debug APK 24 | run: bash ./gradlew assembleDebug --stacktrace 25 | 26 | - name: Upload APK to Github Artifacts 27 | uses: actions/upload-artifact@v1 28 | with: 29 | name: app 30 | path: app/build/outputs/apk/debug/app-debug.apk 31 | 32 | - name: Upload APK to Diawii 33 | uses: rnkdsh/action-upload-diawi@v1.1.0 34 | with: 35 | token: ${{ secrets.DIAWI_TOKEN }} 36 | file: ./app/build/outputs/apk/debug/app-debug.apk 37 | comment: ${{ github.event.head_commit.message }} -------------------------------------------------------------------------------- /.github/workflows/send_apk_slack.yml: -------------------------------------------------------------------------------- 1 | name: Send APK on Slack 2 | on: 3 | push: 4 | branches: 5 | - 'main' 6 | 7 | jobs: 8 | 9 | apk: 10 | name: Send APK on Slack 11 | runs-on: ubuntu-18.04 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: set up JDK 1.8 16 | uses: actions/setup-java@v1 17 | with: 18 | java-version: 1.8 19 | 20 | - name: Grant Permission to Execute 21 | run: chmod +x gradlew 22 | 23 | - name: Build debug APK 24 | run: bash ./gradlew assembleDebug --stacktrace 25 | 26 | - name: Upload APK to Github Artifacts 27 | uses: actions/upload-artifact@v1 28 | with: 29 | name: app 30 | path: app/build/outputs/apk/debug/app-debug.apk 31 | 32 | - name: Send APK to Slack 33 | uses: adrey/slack-file-upload-action@1.0.5 34 | with: 35 | token: ${{ secrets.SLACK_TOKEN }} 36 | path: ./app/build/outputs/apk/debug/app-debug.apk 37 | channel: random 38 | filename: Github Actions App.apk 39 | initial_comment: ${{ github.event.head_commit.message }} -------------------------------------------------------------------------------- /.github/workflows/unit_tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | name: Run Unit Tests 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v1 11 | 12 | # Cache gradle 13 | - name: Cache Gradle and wrapper 14 | uses: actions/cache@v2 15 | with: 16 | path: | 17 | ~/.gradle/caches 18 | ~/.gradle/wrapper 19 | key: cache-${{ runner.os }}-${{ matrix.jdk }}-gradle-${{ hashFiles('**/*.gradle*') }} 20 | restore-keys: | 21 | ${{ runner.os }}-gradle- 22 | - name: Validate Gradle Wrapper 23 | uses: gradle/wrapper-validation-action@v1 24 | 25 | - name: Run Unit tests 26 | run: bash ./gradlew test --stacktrace 27 | -------------------------------------------------------------------------------- /.github/workflows/upload_apk_in_releases.yml: -------------------------------------------------------------------------------- 1 | name: Upload APK in Releases 2 | on: 3 | push: 4 | branches: 5 | - 'main' 6 | 7 | jobs: 8 | apk: 9 | name: Upload APK in Releases 10 | runs-on: ubuntu-18.04 11 | 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: set up JDK 1.8 15 | uses: actions/setup-java@v1 16 | with: 17 | java-version: 1.8 18 | 19 | - name: Grant Permission to Execute 20 | run: chmod +x gradlew 21 | 22 | - name: Build debug APK 23 | run: bash ./gradlew assembleDebug --stacktrace 24 | 25 | - name: Upload APK to Github Artifacts 26 | uses: actions/upload-artifact@v1 27 | with: 28 | name: app 29 | path: app/build/outputs/apk/debug/app-debug.apk 30 | 31 | - name: Create Release 32 | id: create_release 33 | uses: actions/create-release@v1 34 | env: 35 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN_RELEASE }} 36 | with: 37 | tag_name: newtag 38 | release_name: Automatic Release 39 | draft: false 40 | prerelease: false 41 | 42 | - name: Upload APK to Release 43 | id: upload-release-asset 44 | uses: actions/upload-release-asset@v1 45 | env: 46 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN_RELEASE }} 47 | with: 48 | upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps 49 | asset_path: ./app/build/outputs/apk/debug/app-debug.apk 50 | asset_name: app-debug.apk 51 | asset_content_type: application/zip 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /Android-GithubActions-App.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/Android-GithubActions-App.apk -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android-Github-Actions 2 | An sample image gallery app utilizing Unsplash API to play with Github Actions for Android CI/CD. 3 | 4 |
5 | Built with ❤︎ by 6 | Wajahat Karim 7 |
8 |
9 | 10 | - This demo was showcased in a talk live by DSC IBA Karachi. 11 | 12 | ## Github Actions 13 | 14 | * ![Tests](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Tests/badge.svg) Run Unit Tests - [Check unit_tests.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/unit_tests.yml) 15 | * ![Generate APK](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Generate%20APK/badge.svg) Generate APK and upload on Github Artifacts - [Check apk_generate.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/apk_generate.yml) 16 | * ![Upload APK in Releases](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Upload%20APK%20in%20Releases/badge.svg) Upload APK in Github Release - [Check upload_apk_in_releases.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/upload_apk_in_releases.yml) 17 | * ![Send APK on Slack](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Send%20APK%20on%20Slack/badge.svg) Send APK on Slack - [Check send_apk_slack.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/send_apk_slack.yml) 18 | * ![Send APK to AppCenter](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Send%20APK%20to%20AppCenter/badge.svg) Send APK to AppCenter Distribution - [Check send_apk_appcenter.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/send_apk_appcenter.yml) 19 | * ![Send APK to Diawii](https://github.com/wajahatkarim3/Android-Github-Actions/workflows/Send%20APK%20to%20Diawii/badge.svg) Send APK to Diawi - [Check send_apk_diawi.yml](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/.github/workflows/send_apk_diawi.yml) 20 | * Upload APK on Google Play - [Check this detailed article](https://medium.com/scalereal/automate-publishing-app-to-the-google-play-store-with-github-actions-fastlane-ac9104712486) 21 | * Send APK to Firebase Distributions - [Check this detailed articled](https://medium.com/firebase-developers/quickly-distribute-app-with-firebase-app-distribution-using-github-actions-fastlane-c7d8eca18ee0) 22 | * Automatically publish Android library to jCenter with Bintray - [Read this article](https://medium.com/scalereal/automate-publishing-android-library-to-bintray-using-github-actions-9b8ad8ab2698) 23 | 24 | ## Screenshots 25 | 26 |
27 |
28 | 29 |
30 | 31 |
32 | 33 | ## Features 34 | * Popular photos with pagination support 35 | * Quickly explore top categories like Cars, Mountains, Animals, Interior etc. 36 | * Search query with pagination support 37 | * Comes in both light and dark mode. 38 | 39 | ## 📱 Download Demo on Android 40 | Download the [APK file from here](https://github.com/wajahatkarim3/Android-Github-Actions/blob/main/Android-GithubActions-App.apk?raw=true) on your Android phone and enjoy the Demo App :) 41 | 42 | ## 👨 Developed By 43 | 44 | 45 | 46 | 47 | 48 | **Wajahat Karim** 49 | 50 | [![Twitter](https://img.shields.io/badge/-twitter-grey?logo=twitter)](https://twitter.com/WajahatKarim) 51 | [![Web](https://img.shields.io/badge/-web-grey?logo=appveyor)](https://wajahatkarim.com/) 52 | [![Medium](https://img.shields.io/badge/-medium-grey?logo=medium)](https://medium.com/@wajahatkarim3) 53 | [![Linkedin](https://img.shields.io/badge/-linkedin-grey?logo=linkedin)](https://www.linkedin.com/in/wajahatkarim/) 54 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | id 'kotlin-kapt' 5 | id 'kotlin-android-extensions' 6 | } 7 | 8 | android { 9 | compileSdkVersion 30 10 | buildToolsVersion "30.0.2" 11 | 12 | defaultConfig { 13 | applicationId "com.wajahatkarim3.imagine" 14 | minSdkVersion 23 15 | targetSdkVersion 30 16 | versionCode 1 17 | versionName "1.0" 18 | 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | compileOptions { 29 | sourceCompatibility JavaVersion.VERSION_1_8 30 | targetCompatibility JavaVersion.VERSION_1_8 31 | } 32 | kotlinOptions { 33 | jvmTarget = '1.8' 34 | } 35 | sourceSets { 36 | androidTest.java.srcDirs += "src/test-common/java" 37 | test.java.srcDirs += "src/test-common/java" 38 | } 39 | buildFeatures { 40 | viewBinding true 41 | } 42 | androidExtensions { 43 | features = ["parcelize"] 44 | } 45 | } 46 | 47 | dependencies { 48 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 49 | implementation 'androidx.core:core-ktx:1.3.2' 50 | implementation "androidx.appcompat:appcompat:$appcompat_version" 51 | implementation "com.google.android.material:material:$material_version" 52 | implementation "androidx.recyclerview:recyclerview:1.2.0-beta01" 53 | implementation "androidx.constraintlayout:constraintlayout:$constraint_layout_version" 54 | 55 | // Architecture 56 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" 57 | implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" 58 | implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" 59 | 60 | // Navigation 61 | implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" 62 | implementation "androidx.navigation:navigation-ui-ktx:$nav_version" 63 | implementation 'androidx.legacy:legacy-support-v4:1.0.0' 64 | implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" 65 | 66 | // Kotlin Coroutines 67 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" 68 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" 69 | 70 | // Retrofit 71 | implementation "com.google.code.gson:gson:$gson_version" 72 | implementation "com.squareup.retrofit2:retrofit:$retrofit_version" 73 | implementation "com.squareup.retrofit2:converter-gson:$retrofit_version" 74 | implementation "com.squareup.okhttp3:logging-interceptor:4.9.0" 75 | 76 | // Dagger 77 | implementation "com.google.dagger:dagger:$dagger_version" 78 | implementation "com.google.dagger:dagger-android:$dagger_version" 79 | implementation "com.google.dagger:dagger-android-support:$dagger_version" 80 | implementation 'androidx.legacy:legacy-support-v4:1.0.0' 81 | kapt "com.google.dagger:dagger-compiler:$dagger_version" 82 | kapt "com.google.dagger:dagger-android-processor:$dagger_version" 83 | 84 | // Third-party 85 | implementation 'com.google.android:flexbox:2.0.1' 86 | implementation "io.coil-kt:coil:1.1.0" 87 | implementation 'com.github.chrisbanes:PhotoView:2.3.0' 88 | 89 | // Testing 90 | testImplementation 'junit:junit:4.12' 91 | testImplementation "androidx.arch.core:core-testing:2.1.0" 92 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version" 93 | testImplementation "io.mockk:mockk:1.9.3" 94 | testImplementation "com.squareup.okhttp3:mockwebserver:$okhttp_version" 95 | androidTestImplementation 'org.mockito:mockito-android:2.18.3' 96 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 97 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 98 | androidTestImplementation "io.mockk:mockk-android:1.9.3" 99 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/wajahatkarim3/imagine/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.wajahatkarim3.images", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ImagineApp.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine 2 | 3 | import android.app.Application 4 | import androidx.appcompat.app.AppCompatDelegate 5 | import com.wajahatkarim3.imagine.di.components.DaggerAppComponent 6 | import com.wajahatkarim3.imagine.utils.isNight 7 | import dagger.android.AndroidInjector 8 | import dagger.android.DispatchingAndroidInjector 9 | import dagger.android.HasAndroidInjector 10 | import javax.inject.Inject 11 | 12 | class ImagineApp: Application(), HasAndroidInjector { 13 | 14 | @Inject 15 | lateinit var androidInjector: DispatchingAndroidInjector 16 | 17 | override fun onCreate() { 18 | super.onCreate() 19 | initDi() 20 | setupDayNightMode() 21 | } 22 | 23 | fun initDi() { 24 | DaggerAppComponent.builder() 25 | .create(this) 26 | .build() 27 | .inject(this) 28 | } 29 | 30 | override fun androidInjector(): AndroidInjector { 31 | return androidInjector 32 | } 33 | 34 | fun setupDayNightMode() { 35 | // Get UI mode and set 36 | val mode = if (isNight()) { 37 | AppCompatDelegate.MODE_NIGHT_YES 38 | } else { 39 | AppCompatDelegate.MODE_NIGHT_NO 40 | } 41 | 42 | AppCompatDelegate.setDefaultNightMode(mode) 43 | } 44 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/adapters/PhotosAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.adapters 2 | 3 | import android.view.LayoutInflater 4 | import android.view.ViewGroup 5 | import androidx.recyclerview.widget.RecyclerView 6 | import coil.load 7 | import com.wajahatkarim3.imagine.R 8 | import com.wajahatkarim3.imagine.databinding.PhotoItemLayoutBinding 9 | import com.wajahatkarim3.imagine.model.PhotoModel 10 | 11 | class PhotosAdapter(val onPhotoSelected: (photo: PhotoModel, position: Int) -> Unit): RecyclerView.Adapter() { 12 | 13 | private val photoItems: ArrayList = arrayListOf() 14 | 15 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder { 16 | var binding = PhotoItemLayoutBinding.inflate( 17 | LayoutInflater.from(parent.context), 18 | parent, 19 | false 20 | ) 21 | return PhotoViewHolder(binding) 22 | } 23 | 24 | override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) { 25 | holder.bind(photoItems[position], position) 26 | } 27 | 28 | override fun getItemCount() = photoItems.size 29 | 30 | fun updateItems(photosList: List) { 31 | photoItems.clear() 32 | photoItems.addAll(photosList) 33 | notifyDataSetChanged() 34 | } 35 | 36 | inner class PhotoViewHolder(val itemBinding: PhotoItemLayoutBinding): RecyclerView.ViewHolder(itemBinding.root) { 37 | 38 | fun bind(photoModel: PhotoModel, position: Int) { 39 | itemBinding.apply { 40 | imgPhoto.load(photoModel.urls.thumb) { 41 | placeholder(R.color.color_box_background) 42 | crossfade(true) 43 | } 44 | 45 | cardPhoto.setOnClickListener { 46 | onPhotoSelected(photoModel, position) 47 | } 48 | 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/adapters/TagsAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.adapters 2 | 3 | import android.view.LayoutInflater 4 | import android.view.ViewGroup 5 | import androidx.recyclerview.widget.RecyclerView 6 | import coil.load 7 | import com.wajahatkarim3.imagine.R 8 | import com.wajahatkarim3.imagine.databinding.TagItemLayoutBinding 9 | import com.wajahatkarim3.imagine.model.TagModel 10 | 11 | class TagsAdapter(val onTagSelected: (tag: TagModel, position: Int) -> Unit): RecyclerView.Adapter() { 12 | 13 | private val tagItems: ArrayList = arrayListOf() 14 | 15 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagViewHolder { 16 | var binding = TagItemLayoutBinding.inflate( 17 | LayoutInflater.from(parent.context), 18 | parent, 19 | false 20 | ) 21 | return TagViewHolder(binding) 22 | } 23 | 24 | override fun onBindViewHolder(holder: TagViewHolder, position: Int) { 25 | holder.bind(tagItems[position], position) 26 | } 27 | 28 | override fun getItemCount() = tagItems.size 29 | 30 | fun updateItems(tagsList: List) { 31 | tagItems.clear() 32 | tagItems.addAll(tagsList) 33 | notifyDataSetChanged() 34 | } 35 | 36 | inner class TagViewHolder(val itemBinding: TagItemLayoutBinding): RecyclerView.ViewHolder(itemBinding.root) { 37 | 38 | fun bind(tagModel: TagModel, position: Int) { 39 | itemBinding.apply { 40 | txtTagName.text = tagModel.tagName 41 | imgTag.load(tagModel.imageUrl) { 42 | placeholder(R.color.color_box_background) 43 | crossfade(true) 44 | } 45 | 46 | cardTag.setOnClickListener { 47 | onTagSelected(tagModel, position) 48 | } 49 | } 50 | } 51 | 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/base/BaseActivity.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.base 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | 6 | open class BaseActivity : AppCompatActivity() { 7 | override fun onCreate(savedInstanceState: Bundle?) { 8 | super.onCreate(savedInstanceState) 9 | } 10 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/base/BaseFragment.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.base 2 | 3 | import android.content.Context 4 | import androidx.fragment.app.Fragment 5 | import androidx.lifecycle.ViewModelProvider 6 | import dagger.android.support.AndroidSupportInjection 7 | import javax.inject.Inject 8 | 9 | abstract class BaseFragment: Fragment() { 10 | @Inject 11 | lateinit var viewModelProvider: ViewModelProvider.Factory 12 | 13 | override fun onAttach(context: Context) { 14 | AndroidSupportInjection.inject(this) 15 | super.onAttach(context) 16 | } 17 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/DataResource.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data 2 | 3 | /** 4 | * A generic class that holds a value with its loading status. 5 | * @param 6 | */ 7 | data class DataResource( 8 | val status: DataStatus, 9 | val data: T?, 10 | val message: String? 11 | ) { 12 | companion object { 13 | fun success(data: T?): DataResource { 14 | return DataResource(DataStatus.SUCCESS, data, null) 15 | } 16 | 17 | fun error(msg: String, data: T? = null): DataResource { 18 | return DataResource(DataStatus.ERROR, data, msg) 19 | } 20 | } 21 | } 22 | 23 | /** 24 | * Status of a resource that is provided to the UI. 25 | * 26 | * 27 | * These are usually created by the Repository classes where they return 28 | * `LiveData>` to pass back the latest data to the UI with its fetch status. 29 | */ 30 | enum class DataStatus { 31 | SUCCESS, 32 | ERROR 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/DataState.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data 2 | 3 | /** 4 | * A Sealed class to fetch data from server which will be either data or the error. 5 | * @author Wajahat Karim 6 | */ 7 | sealed class DataState { 8 | data class Success(val data: T): DataState() 9 | data class Error(val message: String): DataState() 10 | 11 | companion object { 12 | fun success(data: T) = Success(data) 13 | fun error(message: String) = Error(message) 14 | } 15 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/ApiResponse.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | 4 | import retrofit2.Response 5 | 6 | /** 7 | * Common class used by API responses. 8 | */ 9 | sealed class ApiResponse { 10 | 11 | /** 12 | * API Success response class from retrofit. 13 | * 14 | * [data] is optional. (There are responses without data) 15 | */ 16 | data class ApiSuccessResponse(val response: Response) : ApiResponse() { 17 | val data: T? = response.body() 18 | } 19 | 20 | /** 21 | * Failure class represents two types of Failure: 22 | * 1) ### Error response e.g. server error 23 | * 2) ### Exception response e.g. network connection error 24 | */ 25 | sealed class ApiFailureResponse { 26 | data class Error(val response: Response) : ApiResponse() 27 | 28 | data class Exception(val exception: Throwable) : ApiResponse() { 29 | val message: String? = exception.localizedMessage 30 | } 31 | } 32 | 33 | companion object { 34 | 35 | 36 | /** 37 | * ApiResponse error Factory. 38 | * 39 | * [ApiFailureResponse] factory function. Only receives [Throwable] as an argument. 40 | */ 41 | fun exception(ex: Throwable) = ApiFailureResponse.Exception(ex) 42 | 43 | /** 44 | * ApiResponse error Factory. 45 | * 46 | * [ApiFailureResponse] factory function. 47 | */ 48 | fun error(response: Response) = ApiFailureResponse.Error(response) 49 | 50 | 51 | /** 52 | * ApiResponse Factory. 53 | * 54 | * [create] Create [ApiResponse] from [retrofit2.Response] returning from the block. 55 | * If [retrofit2.Response] has no errors, it creates [ApiResponse.ApiSuccessResponse]. 56 | * If [retrofit2.Response] has errors, it creates [ApiResponse.ApiFailureResponse.Error]. 57 | * If [retrofit2.Response] has occurred exceptions, it creates [ApiResponse.ApiFailureResponse.Exception]. 58 | */ 59 | fun create( 60 | successCodeRange: IntRange = 200..299, 61 | response: Response 62 | ): ApiResponse = try { 63 | if (response.raw().code in successCodeRange) { 64 | ApiSuccessResponse(response) 65 | } else { 66 | ApiFailureResponse.Error(response) 67 | } 68 | } catch (ex: Exception) { 69 | ApiFailureResponse.Exception(ex) 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/ApiResponseCallAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | import okhttp3.Request 4 | import okio.Timeout 5 | import retrofit2.Call 6 | import retrofit2.CallAdapter 7 | import retrofit2.Callback 8 | import retrofit2.Response 9 | import java.lang.reflect.Type 10 | 11 | /** 12 | * A Retrofit adapter that converts the Call into a ApiResponse 13 | */ 14 | class ApiResponseCallAdapter constructor( 15 | private val responseType: Type 16 | ) : CallAdapter>> { 17 | 18 | override fun responseType(): Type { 19 | return responseType 20 | } 21 | 22 | override fun adapt(call: Call): Call> { 23 | return ApiResponseCall(call) 24 | } 25 | 26 | internal class ApiResponseCall(private val call: Call) : Call> { 27 | override fun enqueue(callback: Callback>) { 28 | call.enqueue(object : Callback { 29 | override fun onResponse(call: Call, response: Response) { 30 | val apiResponse = ApiResponse.create(response = response) 31 | callback.onResponse(this@ApiResponseCall, Response.success(apiResponse)) 32 | } 33 | 34 | override fun onFailure(call: Call, t: Throwable) { 35 | callback.onResponse( 36 | this@ApiResponseCall, Response.success(ApiResponse.exception(t)) 37 | ) 38 | } 39 | }) 40 | } 41 | 42 | override fun cancel() = call.cancel() 43 | override fun request(): Request = call.request() 44 | override fun isExecuted() = call.isExecuted 45 | override fun isCanceled() = call.isCanceled 46 | override fun execute(): Response> = 47 | throw UnsupportedOperationException("ApiResponseCallAdapter doesn't support execute") 48 | 49 | override fun timeout(): Timeout = Timeout.NONE 50 | override fun clone(): Call> = this 51 | } 52 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/ApiResponseCallAdapterFactory.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | import retrofit2.Call 4 | import retrofit2.CallAdapter 5 | import retrofit2.Retrofit 6 | import java.lang.reflect.ParameterizedType 7 | import java.lang.reflect.Type 8 | 9 | class ApiResponseCallAdapterFactory : CallAdapter.Factory() { 10 | 11 | override fun get( 12 | returnType: Type, 13 | annotations: Array, 14 | retrofit: Retrofit 15 | ) = when (getRawType(returnType)) { 16 | Call::class.java -> { 17 | val callType = getParameterUpperBound(0, returnType as ParameterizedType) 18 | when (getRawType(callType)) { 19 | ApiResponse::class.java -> { 20 | val responseType = getParameterUpperBound(0, callType as ParameterizedType) 21 | ApiResponseCallAdapter(responseType) 22 | } 23 | else -> null 24 | } 25 | } 26 | else -> null 27 | } 28 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/CoroutinesSuspensions.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | @DslMarker 4 | internal annotation class SuspensionFunction -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/ResponseTransformer.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | /** 4 | * A suspend function for handling success response. 5 | */ 6 | @SuspensionFunction 7 | suspend fun ApiResponse.onSuccessSuspend( 8 | onResult: suspend ApiResponse.ApiSuccessResponse.() -> Unit 9 | ): ApiResponse { 10 | if (this is ApiResponse.ApiSuccessResponse) { 11 | onResult(this) 12 | } 13 | return this 14 | } 15 | 16 | 17 | /** 18 | * A suspend function for handling error response. 19 | */ 20 | @SuspensionFunction 21 | suspend fun ApiResponse.onErrorSuspend( 22 | onResult: suspend ApiResponse.ApiFailureResponse.Error.() -> Unit 23 | ): ApiResponse { 24 | if (this is ApiResponse.ApiFailureResponse.Error) { 25 | onResult(this) 26 | } 27 | return this 28 | } 29 | 30 | 31 | /** 32 | * A suspend function for handling exception response. 33 | */ 34 | @SuspensionFunction 35 | suspend fun ApiResponse.onExceptionSuspend( 36 | onResult: suspend ApiResponse.ApiFailureResponse.Exception.() -> Unit 37 | ): ApiResponse { 38 | if (this is ApiResponse.ApiFailureResponse.Exception) { 39 | onResult(this) 40 | } 41 | return this 42 | } 43 | 44 | 45 | /** A message from the [ApiResponse.ApiFailureResponse.Error]. */ 46 | fun ApiResponse.ApiFailureResponse.Error.message(): String = toString() 47 | 48 | /** A message from the [ApiResponse.ApiFailureResponse.Exception]. */ 49 | fun ApiResponse.ApiFailureResponse.Exception.message(): String = toString() 50 | -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/UnsplashApiService.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | import com.wajahatkarim3.imagine.data.remote.responses.SearchPhotosResponse 4 | import com.wajahatkarim3.imagine.model.PhotoModel 5 | import com.wajahatkarim3.imagine.utils.AppConstants 6 | import retrofit2.Response 7 | import retrofit2.http.GET 8 | import retrofit2.http.Query 9 | 10 | interface UnsplashApiService { 11 | 12 | @GET("photos") 13 | suspend fun loadPhotos( 14 | @Query("page") page: Int = 1, 15 | @Query("per_page") numOfPhotos: Int = 10, 16 | @Query("order_by") orderBy: String = "popular" 17 | ): ApiResponse> 18 | 19 | @GET("search/photos") 20 | suspend fun searchPhotos( 21 | @Query("query") query: String, 22 | @Query("page") page: Int = 1, 23 | @Query("per_page") numOfPhotos: Int = 10, 24 | ): ApiResponse 25 | 26 | companion object { 27 | const val BASE_API_URL = "https://api.unsplash.com/" 28 | } 29 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/remote/responses/SearchPhotosResponse.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote.responses 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | import com.wajahatkarim3.imagine.model.PhotoModel 6 | 7 | data class SearchPhotosResponse( 8 | @Expose @SerializedName("total") val total: Int, 9 | @Expose @SerializedName("total_pages") val totalPages: Int, 10 | @Expose @SerializedName("results") val photosList: List 11 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/repository/ImagineRepository.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.repository 2 | 3 | import com.wajahatkarim3.imagine.data.DataResource 4 | import com.wajahatkarim3.imagine.data.DataState 5 | import com.wajahatkarim3.imagine.model.PhotoModel 6 | import kotlinx.coroutines.flow.Flow 7 | 8 | /** 9 | * ImagineRepository is an interface data layer to handle communication with any data source such as Server or local database. 10 | * @see [ImagineRepositoryImpl] for implementation of this class to utilize Unsplash API. 11 | * @author Wajahat Karim 12 | */ 13 | interface ImagineRepository { 14 | suspend fun loadPhotos(pageNumber: Int, pageSize: Int, orderBy: String): Flow>> 15 | suspend fun searchPhotos(query: String, pageNumber: Int, pageSize: Int): Flow>> 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/repository/ImagineRepositoryImpl.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.repository 2 | 3 | import androidx.annotation.WorkerThread 4 | import com.wajahatkarim3.imagine.data.DataResource 5 | import com.wajahatkarim3.imagine.data.DataState 6 | import com.wajahatkarim3.imagine.data.remote.* 7 | import com.wajahatkarim3.imagine.model.PhotoModel 8 | import com.wajahatkarim3.imagine.utils.StringUtils 9 | import kotlinx.coroutines.Dispatchers 10 | import kotlinx.coroutines.flow.Flow 11 | import kotlinx.coroutines.flow.flow 12 | import kotlinx.coroutines.flow.flowOn 13 | import java.io.IOException 14 | import javax.inject.Inject 15 | 16 | /** 17 | * This is an implementation of [ImagineRepository] to handle communication with [UnsplashApiService] server. 18 | * @author Wajahat Karim 19 | */ 20 | class ImagineRepositoryImpl @Inject constructor( 21 | private val stringUtils: StringUtils, 22 | private val apiService: UnsplashApiService 23 | ): ImagineRepository { 24 | 25 | @WorkerThread 26 | override suspend fun loadPhotos( 27 | pageNumber: Int, 28 | pageSize: Int, 29 | orderBy: String 30 | ): Flow>> { 31 | return flow { 32 | apiService.loadPhotos(pageNumber, pageSize, orderBy).apply { 33 | this.onSuccessSuspend { 34 | data?.let { 35 | emit(DataState.success(it)) 36 | } 37 | } 38 | // handle the case when the API request gets an error response. 39 | // e.g. internal server error. 40 | }.onErrorSuspend { 41 | emit(DataState.error>(message())) 42 | 43 | // handle the case when the API request gets an exception response. 44 | // e.g. network connection error. 45 | }.onExceptionSuspend { 46 | if (this.exception is IOException) { 47 | emit(DataState.error>(stringUtils.noNetworkErrorMessage())) 48 | } else { 49 | emit(DataState.error>(stringUtils.somethingWentWrong())) 50 | } 51 | } 52 | } 53 | } 54 | 55 | override suspend fun searchPhotos( 56 | query: String, 57 | pageNumber: Int, 58 | pageSize: Int 59 | ): Flow>> { 60 | return flow { 61 | apiService.searchPhotos(query, pageNumber, pageSize).apply { 62 | this.onSuccessSuspend { 63 | data?.let { 64 | emit(DataState.success(it.photosList)) 65 | } 66 | } 67 | // handle the case when the API request gets an error response. 68 | // e.g. internal server error. 69 | }.onErrorSuspend { 70 | emit(DataState.error>(message())) 71 | 72 | // handle the case when the API request gets an exception response. 73 | // e.g. network connection error. 74 | }.onExceptionSuspend { 75 | if (this.exception is IOException) { 76 | emit(DataState.error>(stringUtils.noNetworkErrorMessage())) 77 | } else { 78 | emit(DataState.error>(stringUtils.somethingWentWrong())) 79 | } 80 | } 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/usecases/FetchPopularPhotosUsecase.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.usecases 2 | 3 | import com.wajahatkarim3.imagine.data.repository.ImagineRepository 4 | import com.wajahatkarim3.imagine.utils.AppConstants 5 | import javax.inject.Inject 6 | 7 | /** 8 | * A use-case to load the popular photos from Unsplash API. 9 | * @author Wajahat Karim 10 | */ 11 | class FetchPopularPhotosUsecase @Inject constructor(private val repository: ImagineRepository) { 12 | suspend operator fun invoke( 13 | pageNum: Int = 1, 14 | pageSize: Int = AppConstants.API.PHOTOS_PER_PAGE, 15 | orderBy: String = "popular" 16 | ) = repository.loadPhotos( 17 | pageNumber = pageNum, 18 | pageSize = pageSize, 19 | orderBy = orderBy 20 | ) 21 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/data/usecases/SearchPhotosUsecase.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.usecases 2 | 3 | import com.wajahatkarim3.imagine.data.repository.ImagineRepository 4 | import com.wajahatkarim3.imagine.utils.AppConstants 5 | import javax.inject.Inject 6 | 7 | /** 8 | * A use-case to search photos from Unsplash API. 9 | * @author Wajahat Karim 10 | */ 11 | class SearchPhotosUsecase @Inject constructor(private val repository: ImagineRepository) { 12 | suspend operator fun invoke( 13 | query: String, 14 | pageNum: Int = 1, 15 | pageSize: Int = AppConstants.API.PHOTOS_PER_PAGE 16 | ) = repository.searchPhotos( 17 | query = query, 18 | pageNumber = pageNum, 19 | pageSize = pageSize 20 | ) 21 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/components/AppComponent.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.components 2 | 3 | import android.app.Application 4 | import com.wajahatkarim3.imagine.ImagineApp 5 | import com.wajahatkarim3.imagine.di.modules.* 6 | import dagger.BindsInstance 7 | import dagger.Component 8 | import dagger.android.AndroidInjectionModule 9 | import dagger.android.AndroidInjector 10 | import javax.inject.Singleton 11 | 12 | /** 13 | * The Dagger Component which provides the modules used throughout the app 14 | * @author Wajahat Karim 15 | */ 16 | @Singleton 17 | @Component( 18 | modules = [ 19 | AndroidInjectionModule::class, 20 | ActivityModule::class, 21 | FragmentModule::class, 22 | ViewModelsFactoryModule::class, 23 | ViewModelModule::class, 24 | NetworkApiModule::class, 25 | RepositoryModule::class 26 | ] 27 | ) 28 | interface AppComponent : AndroidInjector { 29 | 30 | @Component.Builder 31 | interface Builder { 32 | @BindsInstance 33 | fun create(app: Application): Builder 34 | 35 | fun build(): AppComponent 36 | } 37 | 38 | override fun inject(app: ImagineApp) 39 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/factories/AppViewModelProviderFactory.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.factories 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.lifecycle.ViewModelProvider 5 | import javax.inject.Inject 6 | import javax.inject.Provider 7 | import javax.inject.Singleton 8 | 9 | /** 10 | * The Singleton ViewModelFactory to provide any kind of ViewModels used throughout the app 11 | */ 12 | @Singleton 13 | class AppViewModelProviderFactory @Inject constructor(val viewModelsMap: Map, @JvmSuppressWildcards Provider> ) : ViewModelProvider.NewInstanceFactory() { 14 | override fun create(modelClass: Class): T { 15 | val creator = viewModelsMap[modelClass] ?: viewModelsMap.asIterable().firstOrNull { 16 | modelClass.isAssignableFrom(it.key) 17 | }?.value ?: throw IllegalStateException("Coudln't create ViewModel for $modelClass") 18 | 19 | try { 20 | return creator.get() as T 21 | } catch (exception: Exception) { 22 | throw RuntimeException(exception) 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/ActivityModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import com.wajahatkarim3.imagine.ui.MainActivity 4 | import dagger.Module 5 | import dagger.android.ContributesAndroidInjector 6 | 7 | /** 8 | * The Dagger Module for Activities 9 | * @author Wajahat Karim 10 | */ 11 | @Module 12 | abstract class ActivityModule { 13 | 14 | @ContributesAndroidInjector 15 | abstract fun bindMainActivity(): MainActivity 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/FragmentModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import com.wajahatkarim3.imagine.ui.home.HomeFragment 4 | import com.wajahatkarim3.imagine.ui.photodetails.PhotoDetailsFragment 5 | import dagger.Module 6 | import dagger.android.ContributesAndroidInjector 7 | 8 | /** 9 | * The Dagger Module for Fragments 10 | * @author Wajahat Karim 11 | */ 12 | @Module 13 | abstract class FragmentModule { 14 | 15 | @ContributesAndroidInjector 16 | abstract fun bindHomeFragment(): HomeFragment 17 | 18 | @ContributesAndroidInjector 19 | abstract fun bindPhotoDetailsFragment(): PhotoDetailsFragment 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/NetworkApiModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import com.wajahatkarim3.imagine.BuildConfig 4 | import com.wajahatkarim3.imagine.data.remote.ApiResponseCallAdapterFactory 5 | import com.wajahatkarim3.imagine.data.remote.UnsplashApiService 6 | import com.wajahatkarim3.imagine.utils.AppConstants 7 | import dagger.Module 8 | import dagger.Provides 9 | import okhttp3.OkHttpClient 10 | import okhttp3.logging.HttpLoggingInterceptor 11 | import retrofit2.Retrofit 12 | import retrofit2.converter.gson.GsonConverterFactory 13 | import javax.inject.Singleton 14 | 15 | /** 16 | * The Dagger Module to provide the instances of [OkHttpClient], [Retrofit], and [WordpressApiService] classes. 17 | * @author Wajahat Karim 18 | */ 19 | @Module 20 | class NetworkApiModule { 21 | 22 | @Singleton 23 | @Provides 24 | fun providesOkHttpClient(): OkHttpClient { 25 | val logging = HttpLoggingInterceptor() 26 | logging.setLevel(HttpLoggingInterceptor.Level.BASIC) 27 | 28 | return OkHttpClient.Builder() 29 | .addInterceptor { chain -> 30 | var request = chain.request() 31 | var newRequest = request.newBuilder().header("Authorization", AppConstants.API.API_KEY) 32 | chain.proceed(newRequest.build()) 33 | } 34 | .addInterceptor(logging) 35 | .build() 36 | } 37 | 38 | @Singleton 39 | @Provides 40 | fun providesRetrofit(okHttpClient: OkHttpClient): Retrofit { 41 | return Retrofit.Builder() 42 | .baseUrl(UnsplashApiService.BASE_API_URL) 43 | .client(okHttpClient) 44 | .addConverterFactory(GsonConverterFactory.create()) 45 | .addCallAdapterFactory(ApiResponseCallAdapterFactory()) 46 | .build() 47 | } 48 | 49 | @Singleton 50 | @Provides 51 | fun providesUnsplashApiService(retrofit: Retrofit): UnsplashApiService { 52 | return retrofit.create(UnsplashApiService::class.java) 53 | } 54 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/RepositoryModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import android.app.Application 4 | import com.wajahatkarim3.imagine.data.remote.UnsplashApiService 5 | import com.wajahatkarim3.imagine.data.repository.ImagineRepository 6 | import com.wajahatkarim3.imagine.data.repository.ImagineRepositoryImpl 7 | import com.wajahatkarim3.imagine.utils.StringUtils 8 | import dagger.Module 9 | import dagger.Provides 10 | import javax.inject.Singleton 11 | 12 | /** 13 | * The Dagger Module for providing repository instances. 14 | * @author Wajahat Karim 15 | */ 16 | @Module 17 | class RepositoryModule { 18 | 19 | @Singleton 20 | @Provides 21 | fun provideStringUtils(app: Application): StringUtils { 22 | return StringUtils(app) 23 | } 24 | 25 | @Singleton 26 | @Provides 27 | fun provideImagineRepository(stringUtils: StringUtils, apiService: UnsplashApiService): ImagineRepository { 28 | return ImagineRepositoryImpl(stringUtils, apiService) 29 | } 30 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/ViewModelModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import androidx.lifecycle.ViewModel 4 | import com.wajahatkarim3.imagine.ui.home.HomeViewModel 5 | import com.wajahatkarim3.imagine.ui.photodetails.PhotoDetailsViewModel 6 | import dagger.Binds 7 | import dagger.MapKey 8 | import dagger.Module 9 | import dagger.multibindings.IntoMap 10 | import kotlin.reflect.KClass 11 | 12 | @Target( 13 | AnnotationTarget.FUNCTION, 14 | AnnotationTarget.PROPERTY_SETTER, 15 | AnnotationTarget.PROPERTY_GETTER 16 | ) 17 | @MapKey 18 | annotation class ViewModelKey(val value: KClass) 19 | 20 | /** 21 | * The Dagger Module for creating ViewModels based on the key-value Dagger bindings. 22 | * @author Wajahat Karim 23 | */ 24 | @Module 25 | abstract class ViewModelModule { 26 | @Binds 27 | @IntoMap 28 | @ViewModelKey(HomeViewModel::class) 29 | abstract fun bindHomeViewModel(viewModel: HomeViewModel): ViewModel 30 | 31 | @Binds 32 | @IntoMap 33 | @ViewModelKey(PhotoDetailsViewModel::class) 34 | abstract fun bindPhotoDetailsViewModel(viewModel: PhotoDetailsViewModel): ViewModel 35 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/di/modules/ViewModelsFactoryModule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.di.modules 2 | 3 | import androidx.lifecycle.ViewModelProvider 4 | import com.wajahatkarim3.imagine.di.factories.AppViewModelProviderFactory 5 | import dagger.Binds 6 | import dagger.Module 7 | 8 | /** 9 | * This modules is responsible for creating ViewModels for screens with the help of [AppViewModelProviderFactory]. 10 | * This is required to easily inject dependencies in [ViewModel] as constructor parameters. 11 | * @author Wajahat Karim 12 | */ 13 | @Module 14 | interface ViewModelsFactoryModule { 15 | 16 | @Binds 17 | fun bindAppViewModelFactory(factory: AppViewModelProviderFactory) : ViewModelProvider.Factory 18 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/model/PhotoModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.model 2 | 3 | import android.os.Parcelable 4 | import com.google.gson.annotations.Expose 5 | import kotlinx.android.parcel.Parcelize 6 | 7 | @Parcelize 8 | data class PhotoModel ( 9 | @Expose val id: String, 10 | @Expose val created_at: String, 11 | @Expose val color: String, 12 | @Expose val description: String, 13 | @Expose val urls: PhotoUrlsModel, 14 | @Expose val user: UserModel 15 | ): Parcelable -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/model/PhotoUrlsModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.model 2 | 3 | import android.os.Parcelable 4 | import com.google.gson.annotations.Expose 5 | import kotlinx.android.parcel.Parcelize 6 | 7 | @Parcelize 8 | data class PhotoUrlsModel( 9 | @Expose val raw: String, 10 | @Expose val full: String, 11 | @Expose val regular: String, 12 | @Expose val small: String, 13 | @Expose val thumb: String 14 | ): Parcelable -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/model/TagModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.model 2 | 3 | data class TagModel ( 4 | val tagName: String, 5 | val imageUrl: String 6 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/model/UserModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.model 2 | 3 | import android.os.Parcelable 4 | import com.google.gson.annotations.Expose 5 | import kotlinx.android.parcel.Parcelize 6 | 7 | @Parcelize 8 | data class UserModel( 9 | @Expose val id: String, 10 | @Expose val username: String, 11 | @Expose val name: String 12 | // @Expose val profile_image: String 13 | ): Parcelable -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui 2 | 3 | import android.content.res.Configuration 4 | import android.os.Bundle 5 | import android.view.Menu 6 | import android.view.MenuItem 7 | import androidx.appcompat.app.AppCompatDelegate 8 | import androidx.navigation.NavController 9 | import androidx.navigation.fragment.NavHostFragment 10 | import androidx.navigation.ui.setupActionBarWithNavController 11 | import com.wajahatkarim3.imagine.R 12 | import com.wajahatkarim3.imagine.base.BaseActivity 13 | import com.wajahatkarim3.imagine.databinding.ActivityMainBinding 14 | 15 | class MainActivity : BaseActivity() { 16 | 17 | lateinit var bi: ActivityMainBinding 18 | lateinit var navController: NavController 19 | 20 | override fun onCreate(savedInstanceState: Bundle?) { 21 | super.onCreate(savedInstanceState) 22 | bi = ActivityMainBinding.inflate(layoutInflater) 23 | setContentView(bi.root) 24 | 25 | setupViews() 26 | } 27 | 28 | fun setupViews() { 29 | // Navigation 30 | val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostMain) as NavHostFragment 31 | navController = navHostFragment.navController 32 | setupActionBarWithNavController(navController) 33 | } 34 | 35 | override fun onSupportNavigateUp(): Boolean { 36 | return navController.navigateUp() || super.onSupportNavigateUp() 37 | } 38 | 39 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 40 | menuInflater.inflate(R.menu.menu_main, menu) 41 | return true 42 | } 43 | 44 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 45 | return when (item.itemId) { 46 | R.id.action_day_night_mode -> { 47 | // Get new mode. 48 | val mode = 49 | if ((resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == 50 | Configuration.UI_MODE_NIGHT_NO 51 | ) { 52 | AppCompatDelegate.MODE_NIGHT_YES 53 | } else { 54 | AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY 55 | } 56 | 57 | // Change UI Mode 58 | AppCompatDelegate.setDefaultNightMode(mode) 59 | true 60 | } 61 | else -> super.onOptionsItemSelected(item) 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/home/HomeFragment.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.home 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import android.view.inputmethod.EditorInfo 8 | import androidx.core.os.bundleOf 9 | import androidx.core.widget.NestedScrollView 10 | import androidx.lifecycle.ViewModelProvider 11 | import androidx.navigation.fragment.findNavController 12 | import androidx.recyclerview.widget.GridLayoutManager 13 | import androidx.recyclerview.widget.RecyclerView 14 | import com.google.android.flexbox.AlignItems 15 | import com.google.android.flexbox.FlexDirection 16 | import com.google.android.flexbox.FlexWrap 17 | import com.google.android.flexbox.FlexboxLayoutManager 18 | import com.google.android.material.snackbar.Snackbar 19 | import com.wajahatkarim3.imagine.R 20 | import com.wajahatkarim3.imagine.adapters.PhotosAdapter 21 | import com.wajahatkarim3.imagine.adapters.TagsAdapter 22 | import com.wajahatkarim3.imagine.base.BaseFragment 23 | import com.wajahatkarim3.imagine.databinding.HomeFragmentBinding 24 | import com.wajahatkarim3.imagine.model.TagModel 25 | import com.wajahatkarim3.imagine.ui.MainActivity 26 | import com.wajahatkarim3.imagine.utils.* 27 | 28 | class HomeFragment : BaseFragment() { 29 | 30 | private lateinit var viewModel: HomeViewModel 31 | lateinit var bi: HomeFragmentBinding 32 | 33 | lateinit var tagsAdapter: TagsAdapter 34 | lateinit var photosAdapter: PhotosAdapter 35 | 36 | var snackbar: Snackbar? = null 37 | 38 | override fun onCreateView( 39 | inflater: LayoutInflater, 40 | container: ViewGroup?, 41 | savedInstanceState: Bundle? 42 | ): View? { 43 | bi = HomeFragmentBinding.inflate(inflater, container, false) 44 | return bi.root 45 | } 46 | 47 | override fun onActivityCreated(savedInstanceState: Bundle?) { 48 | super.onActivityCreated(savedInstanceState) 49 | viewModel = ViewModelProvider(this, viewModelProvider).get(HomeViewModel::class.java) 50 | 51 | setupViews() 52 | initTags() 53 | initObservations() 54 | } 55 | 56 | fun setupViews() { 57 | context?.let { ctx -> 58 | // Tags RecyclerView 59 | tagsAdapter = TagsAdapter { tag, position -> 60 | performSearch(tag.tagName) 61 | } 62 | val flexboxLayoutManager = FlexboxLayoutManager(ctx).apply { 63 | flexWrap = FlexWrap.WRAP 64 | flexDirection = FlexDirection.ROW 65 | alignItems = AlignItems.STRETCH 66 | } 67 | bi.recyclerTags.layoutManager = flexboxLayoutManager 68 | bi.recyclerTags.adapter = tagsAdapter 69 | 70 | // Photos RecyclerView 71 | photosAdapter = PhotosAdapter() { photo, position -> 72 | var bundle = bundleOf("photo" to photo) 73 | findNavController().navigate(R.id.action_homeFragment_to_photoDetailsFragment, bundle) 74 | } 75 | photosAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY 76 | bi.recyclerPopularPhotos.adapter = photosAdapter 77 | 78 | // NestedScrollView 79 | bi.nestedScrollView.setOnScrollChangeListener { v: NestedScrollView, scrollX, scrollY, oldScrollX, oldScrollY -> 80 | if (scrollY == v.getChildAt(0).measuredHeight - v.measuredHeight) { 81 | viewModel.loadMorePhotos() 82 | } 83 | } 84 | 85 | // Input Text Search 86 | bi.inputSearchPhotos.setEndIconOnClickListener { 87 | bi.txtSearchPhotos.setText("") 88 | bi.lblPopular.setText(getString(R.string.label_popular_text_str)) 89 | viewModel.fetchPhotos(1) 90 | } 91 | 92 | bi.txtSearchPhotos.setOnEditorActionListener { _, actionId, _ -> 93 | if (actionId == EditorInfo.IME_ACTION_SEARCH) { 94 | bi.txtSearchPhotos.dismissKeyboard() 95 | performSearch(bi.txtSearchPhotos.text.toString()) 96 | true 97 | } 98 | false 99 | } 100 | } 101 | } 102 | 103 | private fun performSearch(query: String) { 104 | bi.txtSearchPhotos.setText(query) 105 | bi.lblPopular.setText(getString(R.string.message_search_results_for_str, query)) 106 | viewModel.searchPhotos(query) 107 | } 108 | 109 | fun initObservations() { 110 | viewModel.uiStateLiveData.observe(viewLifecycleOwner) { state -> 111 | when(state) { 112 | is LoadingState -> { 113 | bi.recyclerPopularPhotos.gone() 114 | bi.progressPhotos.visible() 115 | } 116 | 117 | is LoadingNextPageState -> { 118 | showToast(getString(R.string.message_load_photos_str)) 119 | } 120 | 121 | is ContentState -> { 122 | bi.recyclerPopularPhotos.visible() 123 | bi.progressPhotos.gone() 124 | } 125 | 126 | is ErrorState -> { 127 | bi.progressPhotos.gone() 128 | bi.nestedScrollView.showSnack(state.message, getString(R.string.action_retry_str)) { 129 | viewModel.retry() 130 | } 131 | } 132 | 133 | is ErrorNextPageState -> { 134 | bi.nestedScrollView.showSnack(state.message, getString(R.string.action_retry_str)) { 135 | viewModel.retry() 136 | } 137 | } 138 | } 139 | } 140 | 141 | viewModel.photosListLiveData.observe(viewLifecycleOwner) { photos -> 142 | photosAdapter.updateItems(photos) 143 | } 144 | } 145 | 146 | fun initTags() { 147 | var tags = arrayListOf( 148 | TagModel( 149 | tagName = "Food", 150 | imageUrl = "https://www.helpguide.org/wp-content/uploads/fast-foods-candy-cookies-pastries-768.jpg" 151 | ), 152 | TagModel( 153 | tagName = "Cars", 154 | imageUrl = "https://i.dawn.com/primary/2019/03/5c8da9fc3e386.jpg" 155 | ), 156 | TagModel( 157 | tagName = "Cities", 158 | imageUrl = "https://news.mit.edu/sites/default/files/styles/news_article__image_gallery/public/images/201306/20130603150017-0_0.jpg?itok=fU2rLfB6" 159 | ), 160 | TagModel( 161 | tagName = "Mountains", 162 | imageUrl = "https://www.dw.com/image/48396304_101.jpg" 163 | ), 164 | TagModel( 165 | tagName = "People", 166 | imageUrl = "https://cdn.lifehack.org/wp-content/uploads/2015/02/what-makes-people-happy.jpeg" 167 | ), 168 | TagModel( 169 | tagName = "Work", 170 | imageUrl = "https://www.plays-in-business.com/wp-content/uploads/2015/05/successful-business-meeting.jpg" 171 | ), 172 | TagModel( 173 | tagName = "Fashion", 174 | imageUrl = "https://www.remixmagazine.com/assets/Prada-SS21-1__ResizedImageWzg2Niw1NzZd.jpg" 175 | ), 176 | TagModel( 177 | tagName = "Animals", 178 | imageUrl = "https://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/A-G/cheetah-mom-cubs.adapt.470.1.jpg" 179 | ), 180 | TagModel( 181 | tagName = "Interior", 182 | imageUrl = "https://images.homify.com/c_fill,f_auto,q_0,w_740/v1495001963/p/photo/image/2013905/CAM_2_OPTION_1.jpg" 183 | ) 184 | ) 185 | tagsAdapter.updateItems(tags) 186 | } 187 | 188 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/home/HomeUiState.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.home 2 | 3 | sealed class HomeUiState 4 | 5 | object LoadingState: HomeUiState() 6 | object LoadingNextPageState: HomeUiState() 7 | object ContentState: HomeUiState() 8 | object ContentNextPageState: HomeUiState() 9 | object EmptyState: HomeUiState() 10 | class ErrorState(val message: String) : HomeUiState() 11 | class ErrorNextPageState(val message: String) : HomeUiState() -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/home/HomeViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.home 2 | 3 | import androidx.lifecycle.* 4 | import com.wajahatkarim3.imagine.data.DataState 5 | import com.wajahatkarim3.imagine.data.usecases.FetchPopularPhotosUsecase 6 | import com.wajahatkarim3.imagine.data.usecases.SearchPhotosUsecase 7 | import com.wajahatkarim3.imagine.model.PhotoModel 8 | import kotlinx.coroutines.flow.collect 9 | import kotlinx.coroutines.launch 10 | import javax.inject.Inject 11 | 12 | class HomeViewModel @Inject constructor( 13 | private val fetchPopularPhotosUsecase: FetchPopularPhotosUsecase, 14 | private val searchPhotosUsecase: SearchPhotosUsecase 15 | ) : ViewModel() { 16 | 17 | private var _uiState = MutableLiveData() 18 | var uiStateLiveData: LiveData = _uiState 19 | 20 | private var _photosList = MutableLiveData>() 21 | var photosListLiveData: LiveData> = _photosList 22 | 23 | private var pageNumber = 1 24 | private var searchQuery: String = "" 25 | 26 | init { 27 | fetchPhotos(pageNumber) 28 | } 29 | 30 | fun loadMorePhotos() { 31 | pageNumber++ 32 | if (searchQuery == "") 33 | fetchPhotos(pageNumber) 34 | else 35 | searchPhotos(searchQuery, pageNumber) 36 | } 37 | 38 | fun retry() { 39 | if (searchQuery == "") 40 | fetchPhotos(pageNumber) 41 | else 42 | searchPhotos(searchQuery, pageNumber) 43 | } 44 | 45 | fun searchPhotos(query: String) { 46 | searchQuery = query 47 | pageNumber = 1 48 | searchPhotos(query, pageNumber) 49 | } 50 | 51 | fun fetchPhotos(page: Int) { 52 | _uiState.postValue(if (page == 1) LoadingState else LoadingNextPageState) 53 | viewModelScope.launch { 54 | fetchPopularPhotosUsecase(page).collect { dataState -> 55 | when(dataState) { 56 | is DataState.Success -> { 57 | if (page == 1) { 58 | // First page 59 | _uiState.postValue(ContentState) 60 | _photosList.postValue(dataState.data) 61 | } else { 62 | // Any other page 63 | _uiState.postValue(ContentNextPageState) 64 | var currentList = arrayListOf() 65 | _photosList.value?.let { currentList.addAll(it) } 66 | currentList.addAll(dataState.data) 67 | _photosList.postValue(currentList) 68 | } 69 | } 70 | 71 | is DataState.Error -> { 72 | if (page == 1) { 73 | _uiState.postValue(ErrorState(dataState.message)) 74 | } else { 75 | _uiState.postValue(ErrorNextPageState(dataState.message)) 76 | } 77 | } 78 | } 79 | } 80 | } 81 | } 82 | 83 | private fun searchPhotos(query: String, page: Int) { 84 | _uiState.postValue(if (page == 1) LoadingState else LoadingNextPageState) 85 | viewModelScope.launch { 86 | searchPhotosUsecase(query, page).collect { dataState -> 87 | when(dataState) { 88 | is DataState.Success -> { 89 | if (page == 1) { 90 | // First page 91 | _uiState.postValue(ContentState) 92 | _photosList.postValue(dataState.data) 93 | } else { 94 | // Any other page 95 | _uiState.postValue(ContentNextPageState) 96 | var currentList = arrayListOf() 97 | _photosList.value?.let { currentList.addAll(it) } 98 | currentList.addAll(dataState.data) 99 | _photosList.postValue(currentList) 100 | } 101 | } 102 | 103 | is DataState.Error -> { 104 | if (page == 1) { 105 | _uiState.postValue(ErrorState(dataState.message)) 106 | } else { 107 | _uiState.postValue(ErrorNextPageState(dataState.message)) 108 | } 109 | } 110 | } 111 | } 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/photodetails/PhotoDetailsFragment.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.photodetails 2 | 3 | import androidx.lifecycle.ViewModelProvider 4 | import android.os.Bundle 5 | import androidx.fragment.app.Fragment 6 | import android.view.LayoutInflater 7 | import android.view.View 8 | import android.view.ViewGroup 9 | import androidx.navigation.fragment.findNavController 10 | import coil.load 11 | import com.wajahatkarim3.imagine.R 12 | import com.wajahatkarim3.imagine.base.BaseFragment 13 | import com.wajahatkarim3.imagine.databinding.PhotoDetailsFragmentBinding 14 | import com.wajahatkarim3.imagine.model.PhotoModel 15 | 16 | class PhotoDetailsFragment : BaseFragment() { 17 | 18 | private lateinit var viewModel: PhotoDetailsViewModel 19 | private lateinit var bi: PhotoDetailsFragmentBinding 20 | 21 | override fun onCreateView( 22 | inflater: LayoutInflater, container: ViewGroup?, 23 | savedInstanceState: Bundle? 24 | ): View? { 25 | bi = PhotoDetailsFragmentBinding.inflate(inflater, container, false) 26 | return bi.root 27 | } 28 | 29 | override fun onActivityCreated(savedInstanceState: Bundle?) { 30 | super.onActivityCreated(savedInstanceState) 31 | viewModel = ViewModelProvider(this, viewModelProvider).get(PhotoDetailsViewModel::class.java) 32 | 33 | var photo = arguments?.getParcelable("photo") 34 | if (photo == null) { 35 | findNavController().popBackStack() 36 | return 37 | } 38 | 39 | setupViews() 40 | initObservations() 41 | 42 | viewModel.initPhotoModel(photo) 43 | } 44 | 45 | fun setupViews() { 46 | 47 | } 48 | 49 | fun initObservations() { 50 | viewModel.photoModelLiveData.observe(viewLifecycleOwner) { photo -> 51 | bi.photoView.load(photo.urls.full) 52 | } 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/photodetails/PhotoDetailsUiState.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.photodetails 2 | 3 | sealed class PhotoDetailsUiState 4 | 5 | object LoadingState: PhotoDetailsUiState() 6 | object ContentState: PhotoDetailsUiState() 7 | class ErrorState(val message: String) : PhotoDetailsUiState() -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/ui/photodetails/PhotoDetailsViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.photodetails 2 | 3 | import androidx.lifecycle.LiveData 4 | import androidx.lifecycle.MutableLiveData 5 | import androidx.lifecycle.ViewModel 6 | import com.wajahatkarim3.imagine.model.PhotoModel 7 | import javax.inject.Inject 8 | 9 | class PhotoDetailsViewModel @Inject constructor() : ViewModel() { 10 | 11 | private var _uiState = MutableLiveData() 12 | var uiStateLiveData: LiveData = _uiState 13 | 14 | private var _photoModel = MutableLiveData() 15 | var photoModelLiveData: LiveData = _photoModel 16 | 17 | fun initPhotoModel(photo: PhotoModel) { 18 | _photoModel.value = photo 19 | } 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/utils/AppConstants.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.utils 2 | 3 | import com.wajahatkarim3.imagine.BuildConfig 4 | 5 | object AppConstants { 6 | object API { 7 | val PHOTOS_PER_PAGE = 30 8 | val API_KEY = "Client-ID wxl8gDYQvKHvTcfTzfFJ2Fy0GoSuKoJovMopdieYBvk" 9 | } 10 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/utils/StringUtils.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.utils 2 | 3 | import android.app.Application 4 | import com.wajahatkarim3.imagine.R 5 | 6 | class StringUtils(val appContext: Application) { 7 | fun noNetworkErrorMessage() = appContext.getString(R.string.message_no_network_connected_str) 8 | fun somethingWentWrong() = appContext.getString(R.string.message_something_went_wrong_str) 9 | } -------------------------------------------------------------------------------- /app/src/main/java/com/wajahatkarim3/imagine/utils/TheKtx.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.utils 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import android.view.inputmethod.InputMethodManager 6 | import android.widget.EditText 7 | import android.widget.Toast 8 | import androidx.core.content.ContextCompat.getSystemService 9 | import androidx.fragment.app.Fragment 10 | import com.google.android.material.snackbar.Snackbar 11 | import java.util.* 12 | 13 | 14 | fun View.visible() { 15 | visibility = View.VISIBLE 16 | } 17 | 18 | fun View.gone() { 19 | visibility = View.GONE 20 | } 21 | 22 | fun View.invisible() { 23 | visibility = View.INVISIBLE 24 | } 25 | 26 | fun View.showSnack(message: String, action: String = "", actionListener: () -> Unit = {}): Snackbar { 27 | var snackbar = Snackbar.make(this, message, Snackbar.LENGTH_SHORT) 28 | if (action != "") { 29 | snackbar.duration = Snackbar.LENGTH_INDEFINITE 30 | snackbar.setAction(action) { 31 | actionListener() 32 | snackbar.dismiss() 33 | } 34 | } 35 | snackbar.show() 36 | return snackbar 37 | } 38 | 39 | fun Fragment.showToast(message: String) { 40 | Toast.makeText(context, message, Toast.LENGTH_SHORT).show() 41 | } 42 | 43 | fun EditText.dismissKeyboard() { 44 | val imm: InputMethodManager? = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? 45 | imm?.hideSoftInputFromWindow(windowToken, 0) 46 | } 47 | 48 | /** 49 | * Returns [Boolean] based on current time. 50 | * Returns true if hours are between 06:00 pm - 07:00 am 51 | */ 52 | fun isNight(): Boolean { 53 | val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) 54 | return (currentHour <= 7 || currentHour >= 18) 55 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_bedtime_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_search_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/layout/home_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 17 | 18 | 26 | 27 | 41 | 42 | 53 | 54 | 55 | 56 | 57 | 58 | 68 | 69 | 81 | 82 | 92 | 93 | 104 | 105 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /app/src/main/res/layout/photo_details_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/photo_item_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 18 | 19 | 22 | 23 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/res/layout/tag_item_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 19 | 20 | 23 | 24 | 34 | 35 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/navigation/main_nav_graph.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 16 | 17 | 18 | 23 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #1DD196 4 | #16B581 5 | #EFEFEF 6 | #CDDC39 7 | #B2BF30 8 | #2C2C2C 9 | #FF000000 10 | #FFFFFFFF 11 | #232323 12 | #E4E4E4 13 | #ED6E6E 14 | #616161 15 | 16 | #575757 17 | #88DADADA 18 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #138C64 4 | #086747 5 | #EFEFEF 6 | #CDDC39 7 | #B2BF30 8 | #2C2C2C 9 | #FF000000 10 | #FFFFFFFF 11 | #F7F7F7 12 | #4C4C4C 13 | #AC0000 14 | #F7F7F7 15 | 16 | #FFFFFF 17 | #C1C1C1 18 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Imagine 3 | 4 | 5 | Home 6 | Photo Details 7 | 8 | 9 | Search photos 10 | 11 | 12 | Explore 13 | Popular 14 | Loading more photos... 15 | Retry 16 | No network connected! 17 | Something went wrong! 18 | Search results for %1s 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | 12 | 31 | 32 | 33 | 40 | 41 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /app/src/test-common/java/MockTestUtil.kt: -------------------------------------------------------------------------------- 1 | import com.wajahatkarim3.imagine.data.remote.responses.SearchPhotosResponse 2 | import com.wajahatkarim3.imagine.model.PhotoModel 3 | import com.wajahatkarim3.imagine.model.PhotoUrlsModel 4 | import com.wajahatkarim3.imagine.model.UserModel 5 | 6 | class MockTestUtil { 7 | companion object { 8 | fun createPhotos(count: Int): List { 9 | return (0 until count).map { 10 | PhotoModel( 11 | id = "$it", 12 | created_at = "2016-05-03T11:00:28-04:00", 13 | color = "#60544D", 14 | description = "A man drinking a coffee.", 15 | urls = createPhotoUrls(), 16 | user = createUser(it) 17 | ) 18 | } 19 | } 20 | 21 | fun createPhotoUrls(): PhotoUrlsModel { 22 | return PhotoUrlsModel( 23 | raw = "", 24 | full = "", 25 | regular = "", 26 | small = "", 27 | thumb = "" 28 | ) 29 | } 30 | 31 | fun createUser(position: Int): UserModel { 32 | return UserModel( 33 | id = "$position", 34 | username = "username{$position}", 35 | name = "User Full Name $position" 36 | ) 37 | } 38 | 39 | fun createSearchPhotosResponse(): SearchPhotosResponse { 40 | return SearchPhotosResponse( 41 | total = 3, 42 | totalPages = 1, 43 | photosList = createPhotos(3) 44 | ) 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/MainCoroutinesRule.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine 2 | 3 | import kotlinx.coroutines.Dispatchers 4 | import kotlinx.coroutines.ExperimentalCoroutinesApi 5 | import kotlinx.coroutines.test.TestCoroutineDispatcher 6 | import kotlinx.coroutines.test.TestCoroutineScope 7 | import kotlinx.coroutines.test.resetMain 8 | import kotlinx.coroutines.test.setMain 9 | import org.junit.rules.TestWatcher 10 | import org.junit.runner.Description 11 | 12 | 13 | @ExperimentalCoroutinesApi 14 | class MainCoroutinesRule( 15 | val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher() 16 | ) : TestWatcher(), TestCoroutineScope by TestCoroutineScope() { 17 | 18 | override fun starting(description: Description?) { 19 | super.starting(description) 20 | Dispatchers.setMain(testDispatcher) 21 | } 22 | 23 | override fun finished(description: Description?) { 24 | super.finished(description) 25 | Dispatchers.resetMain() 26 | testDispatcher.cleanupTestCoroutines() 27 | } 28 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/remote/ApiResponseTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | import org.hamcrest.CoreMatchers 4 | import org.hamcrest.MatcherAssert 5 | import org.junit.After 6 | import org.junit.Before 7 | 8 | import org.junit.Assert.* 9 | import org.junit.Test 10 | import org.junit.runner.RunWith 11 | import org.junit.runners.JUnit4 12 | import retrofit2.Response 13 | 14 | @RunWith(JUnit4::class) 15 | class ApiResponseTest { 16 | 17 | @Before 18 | fun setUp() { 19 | } 20 | 21 | @After 22 | fun tearDown() { 23 | } 24 | 25 | @Test 26 | fun `test message is not null or empty in Exception response`() { 27 | val exception = Exception("message") 28 | val apiResponse = ApiResponse.exception(exception) 29 | MatcherAssert.assertThat(apiResponse.message, CoreMatchers.`is`("message")) 30 | } 31 | 32 | @Test 33 | fun `test data is is not null in Success response`() { 34 | val apiResponse = ApiResponse.create(200..299, Response.success("test_body")) 35 | if (apiResponse is ApiResponse.ApiSuccessResponse) { 36 | MatcherAssert.assertThat(apiResponse.data, CoreMatchers.notNullValue()) 37 | MatcherAssert.assertThat(apiResponse.data, CoreMatchers.`is`("test_body")) 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/remote/UnsplashApiServiceTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote 2 | 3 | import com.wajahatkarim3.imagine.MainCoroutinesRule 4 | import com.wajahatkarim3.imagine.data.remote.api.ApiAbstract 5 | import kotlinx.coroutines.runBlocking 6 | import org.hamcrest.CoreMatchers.`is` 7 | import org.junit.After 8 | import org.junit.Before 9 | 10 | import org.junit.Assert.* 11 | import org.junit.Rule 12 | import org.junit.Test 13 | import java.io.IOException 14 | 15 | class UnsplashApiServiceTest: ApiAbstract() { 16 | 17 | private lateinit var apiService: UnsplashApiService 18 | 19 | @get:Rule 20 | var coroutineRule = MainCoroutinesRule() 21 | 22 | @Before 23 | fun setUp() { 24 | apiService = createService(UnsplashApiService::class.java) 25 | } 26 | 27 | @After 28 | fun tearDown() { 29 | } 30 | 31 | @Throws(IOException::class) 32 | @Test 33 | fun `test loadPhotos() returns list of Photos`() = runBlocking { 34 | // Given 35 | enqueueResponse("/photos_list_response.json") 36 | 37 | // Invoke 38 | val response = apiService.loadPhotos(1, 10, "") 39 | val responseBody = requireNotNull((response as ApiResponse.ApiSuccessResponse).data) 40 | mockWebServer.takeRequest() 41 | 42 | // Then 43 | assertThat(responseBody[0].id, `is`("LBI7cgq3pbM")) 44 | assertThat(responseBody[0].color, `is`("#60544D")) 45 | assertThat(responseBody[0].urls.thumb, `is`("https://images.unsplash.com/face-springmorning.jpg?q=75&fm=jpg&w=200&fit=max")) 46 | assertThat(responseBody[0].user.id, `is`("pXhwzz1JtQU")) 47 | assertThat(responseBody[0].user.username, `is`("poorkane")) 48 | } 49 | 50 | @Throws(IOException::class) 51 | @Test 52 | fun `test searchPhotos() returns list of Photos`() = runBlocking { 53 | // Given 54 | enqueueResponse("/search_photos_response.json") 55 | 56 | // Invoke 57 | val response = apiService.searchPhotos("", 1, 10) 58 | val responseBody = requireNotNull((response as ApiResponse.ApiSuccessResponse).data) 59 | mockWebServer.takeRequest() 60 | 61 | // Then 62 | assertThat(responseBody.total, `is`(133)) 63 | assertThat(responseBody.totalPages, `is`(7)) 64 | assertThat(responseBody.photosList.size, `is`(1)) 65 | 66 | assertThat(responseBody.photosList[0].id, `is`("eOLpJytrbsQ")) 67 | assertThat(responseBody.photosList[0].color, `is`("#A7A2A1")) 68 | assertThat(responseBody.photosList[0].urls.thumb, `is`("https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef")) 69 | assertThat(responseBody.photosList[0].user.id, `is`("Ul0QVz12Goo")) 70 | assertThat(responseBody.photosList[0].user.username, `is`("ugmonk")) 71 | } 72 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/remote/api/ApiAbstract.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote.api 2 | 3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule 4 | import com.wajahatkarim3.imagine.data.remote.ApiResponseCallAdapterFactory 5 | import okhttp3.mockwebserver.MockResponse 6 | import okhttp3.mockwebserver.MockWebServer 7 | import okhttp3.mockwebserver.RecordedRequest 8 | import okio.buffer 9 | import okio.source 10 | import org.hamcrest.CoreMatchers 11 | import org.hamcrest.MatcherAssert 12 | import org.junit.After 13 | import org.junit.Before 14 | import org.junit.Rule 15 | import org.junit.runner.RunWith 16 | import org.junit.runners.JUnit4 17 | import retrofit2.Retrofit 18 | import retrofit2.converter.gson.GsonConverterFactory 19 | import java.io.IOException 20 | import java.nio.charset.StandardCharsets 21 | 22 | @RunWith(JUnit4::class) 23 | abstract class ApiAbstract { 24 | @Rule 25 | @JvmField 26 | val instantExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule() 27 | 28 | protected lateinit var mockWebServer: MockWebServer 29 | 30 | @Throws(IOException::class) 31 | @Before 32 | fun mockServer() { 33 | mockWebServer = MockWebServer() 34 | mockWebServer.start() 35 | } 36 | 37 | @Throws(IOException::class) 38 | @After 39 | fun stopServer() { 40 | mockWebServer.shutdown() 41 | } 42 | 43 | @Throws(IOException::class) 44 | fun enqueueResponse(fileName: String) { 45 | enqueueResponse(fileName, emptyMap()) 46 | } 47 | 48 | @Throws(IOException::class) 49 | private fun enqueueResponse(fileName: String, headers: Map) { 50 | val inputStream = javaClass.classLoader!!.getResourceAsStream("api-response/$fileName") 51 | val source = inputStream.source().buffer() 52 | val mockResponse = MockResponse() 53 | for ((key, value) in headers) { 54 | mockResponse.addHeader(key, value) 55 | } 56 | mockWebServer.enqueue(mockResponse.setBody(source.readString(StandardCharsets.UTF_8))) 57 | } 58 | 59 | fun createService(clazz: Class): T { 60 | return Retrofit.Builder() 61 | .baseUrl(mockWebServer.url("/")) 62 | .addConverterFactory(GsonConverterFactory.create()) 63 | .addCallAdapterFactory(ApiResponseCallAdapterFactory()) 64 | .build() 65 | .create(clazz) 66 | } 67 | 68 | fun assertRequestPath(path: String) { 69 | val request: RecordedRequest = mockWebServer.takeRequest() 70 | MatcherAssert.assertThat(request.path, CoreMatchers.`is`(path)) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/remote/api/ApiUtil.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.remote.api 2 | 3 | import com.wajahatkarim3.imagine.data.remote.ApiResponse 4 | import retrofit2.Response 5 | 6 | object ApiUtil { 7 | 8 | fun successCall(data: T) = createCall(Response.success(data)) 9 | 10 | fun createCall(response: Response): ApiResponse = 11 | ApiResponse.create(200..229, response) 12 | 13 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/repository/ImagineRepositoryImplTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.repository 2 | 3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule 4 | import com.wajahatkarim3.imagine.MainCoroutinesRule 5 | import com.wajahatkarim3.imagine.data.DataState 6 | import com.wajahatkarim3.imagine.data.remote.ApiResponse 7 | import com.wajahatkarim3.imagine.data.remote.UnsplashApiService 8 | import com.wajahatkarim3.imagine.data.remote.api.ApiUtil.createCall 9 | import com.wajahatkarim3.imagine.data.remote.api.ApiUtil.successCall 10 | import com.wajahatkarim3.imagine.data.remote.message 11 | import com.wajahatkarim3.imagine.data.remote.responses.SearchPhotosResponse 12 | import com.wajahatkarim3.imagine.model.PhotoModel 13 | import com.wajahatkarim3.imagine.utils.StringUtils 14 | import io.mockk.* 15 | import io.mockk.impl.annotations.MockK 16 | import kotlinx.coroutines.flow.count 17 | import kotlinx.coroutines.flow.first 18 | import kotlinx.coroutines.runBlocking 19 | import okhttp3.MediaType.Companion.toMediaTypeOrNull 20 | import okhttp3.ResponseBody.Companion.toResponseBody 21 | import org.hamcrest.CoreMatchers 22 | import org.hamcrest.MatcherAssert 23 | import org.junit.After 24 | import org.junit.Before 25 | 26 | import org.junit.Assert.* 27 | import org.junit.Rule 28 | import org.junit.Test 29 | import org.junit.runner.RunWith 30 | import org.junit.runners.JUnit4 31 | import org.mockito.Mockito.verifyNoMoreInteractions 32 | import org.mockito.internal.util.MockUtil 33 | import retrofit2.Response 34 | 35 | @RunWith(JUnit4::class) 36 | class ImagineRepositoryTest { 37 | 38 | // Subject under test 39 | private lateinit var repository: ImagineRepositoryImpl 40 | 41 | @MockK 42 | private lateinit var apiService: UnsplashApiService 43 | 44 | @MockK 45 | private lateinit var stringUtils: StringUtils 46 | 47 | @get:Rule 48 | var coroutinesRule = MainCoroutinesRule() 49 | 50 | @get:Rule 51 | var instantExecutorRule = InstantTaskExecutorRule() 52 | 53 | @Before 54 | fun setUp() { 55 | MockKAnnotations.init(this) 56 | } 57 | 58 | @After 59 | fun tearDown() { 60 | } 61 | 62 | @Test 63 | fun `test loadPhotos() gives list of photos`() = runBlocking { 64 | // Given 65 | repository = ImagineRepositoryImpl(stringUtils, apiService) 66 | val givenPhotosList = MockTestUtil.createPhotos(3) 67 | val apiCall = successCall(givenPhotosList) 68 | 69 | // When 70 | coEvery { apiService.loadPhotos(any(), any(), any()) } 71 | .returns(apiCall) 72 | 73 | // Invoke 74 | val apiResponseFlow = repository.loadPhotos(1, 1, "") 75 | 76 | // Then 77 | MatcherAssert.assertThat(apiResponseFlow, CoreMatchers.notNullValue()) 78 | 79 | val photosListDataState = apiResponseFlow.first() 80 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.notNullValue()) 81 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.instanceOf(DataState.Success::class.java)) 82 | 83 | val photosList = (photosListDataState as DataState.Success).data 84 | MatcherAssert.assertThat(photosList, CoreMatchers.notNullValue()) 85 | MatcherAssert.assertThat(photosList.size, CoreMatchers.`is`(givenPhotosList.size)) 86 | 87 | coVerify(exactly = 1) { apiService.loadPhotos(any(), any(), any()) } 88 | confirmVerified(apiService) 89 | } 90 | 91 | @Test 92 | fun `test loadPhotos() gives empty list of photos`() = runBlocking { 93 | // Given 94 | repository = ImagineRepositoryImpl(stringUtils, apiService) 95 | val givenPhotosList = MockTestUtil.createPhotos(0) 96 | val apiCall = successCall(givenPhotosList) 97 | 98 | // When 99 | coEvery { apiService.loadPhotos(any(), any(), any()) } 100 | .returns(apiCall) 101 | 102 | // Invoke 103 | val apiResponseFlow = repository.loadPhotos(1, 1, "") 104 | 105 | // Then 106 | MatcherAssert.assertThat(apiResponseFlow, CoreMatchers.notNullValue()) 107 | 108 | val photosListDataState = apiResponseFlow.first() 109 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.notNullValue()) 110 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.instanceOf(DataState.Success::class.java)) 111 | 112 | val photosList = (photosListDataState as DataState.Success).data 113 | MatcherAssert.assertThat(photosList, CoreMatchers.notNullValue()) 114 | MatcherAssert.assertThat(photosList.size, CoreMatchers.`is`(givenPhotosList.size)) 115 | 116 | coVerify(exactly = 1) { apiService.loadPhotos(any(), any(), any()) } 117 | confirmVerified(apiService) 118 | } 119 | 120 | @Test 121 | fun `test loadPhotos() throws exception`() = runBlocking { 122 | // Given 123 | repository = ImagineRepositoryImpl(stringUtils, apiService) 124 | val givenMessage = "Test Error Message" 125 | val exception = Exception(givenMessage) 126 | val apiResponse = ApiResponse.exception>(exception) 127 | 128 | // When 129 | coEvery { apiService.loadPhotos(any(), any(), any()) } 130 | .returns(apiResponse) 131 | coEvery { stringUtils.somethingWentWrong() } 132 | .returns(givenMessage) 133 | 134 | // Invoke 135 | val apiResponseFlow = repository.loadPhotos(1, 1, "") 136 | 137 | // Then 138 | MatcherAssert.assertThat(apiResponseFlow, CoreMatchers.notNullValue()) 139 | MatcherAssert.assertThat(apiResponseFlow.count(), CoreMatchers.`is`(1)) 140 | 141 | val apiResponseDataState = apiResponseFlow.first() 142 | MatcherAssert.assertThat(apiResponseDataState, CoreMatchers.notNullValue()) 143 | MatcherAssert.assertThat(apiResponseDataState, CoreMatchers.instanceOf(DataState.Error::class.java)) 144 | 145 | val errorMessage = (apiResponseDataState as DataState.Error).message 146 | MatcherAssert.assertThat(errorMessage, CoreMatchers.notNullValue()) 147 | MatcherAssert.assertThat(errorMessage, CoreMatchers.equalTo(givenMessage)) 148 | 149 | coVerify(atLeast = 1) { apiService.loadPhotos(any(), any(), any()) } 150 | confirmVerified(apiService) 151 | } 152 | 153 | @Test 154 | fun `test loadPhotos() gives network error`() = runBlocking { 155 | // Given 156 | repository = ImagineRepositoryImpl(stringUtils, apiService) 157 | val givenMessage = "Test Error Message" 158 | val body = givenMessage.toResponseBody("text/html".toMediaTypeOrNull()) 159 | val apiResponse = ApiResponse.error>(Response.error(500, body)) 160 | 161 | // When 162 | coEvery { apiService.loadPhotos(any(), any(), any()) } 163 | .returns(apiResponse) 164 | coEvery { stringUtils.somethingWentWrong() } 165 | .returns(givenMessage) 166 | 167 | // Invoke 168 | val apiResponseFlow = repository.loadPhotos(1, 1, "") 169 | 170 | // Then 171 | MatcherAssert.assertThat(apiResponseFlow, CoreMatchers.notNullValue()) 172 | MatcherAssert.assertThat(apiResponseFlow.count(), CoreMatchers.`is`(1)) 173 | 174 | val apiResponseDataState = apiResponseFlow.first() 175 | MatcherAssert.assertThat(apiResponseDataState, CoreMatchers.notNullValue()) 176 | MatcherAssert.assertThat(apiResponseDataState, CoreMatchers.instanceOf(DataState.Error::class.java)) 177 | 178 | val errorMessage = (apiResponseDataState as DataState.Error).message 179 | MatcherAssert.assertThat(errorMessage, CoreMatchers.notNullValue()) 180 | MatcherAssert.assertThat(errorMessage, CoreMatchers.equalTo(apiResponse.message())) 181 | 182 | coVerify(atLeast = 1) { apiService.loadPhotos(any(), any(), any()) } 183 | confirmVerified(apiService) 184 | } 185 | 186 | @Test 187 | fun `test searchPhotos() gives list of photos`() = runBlocking { 188 | // Given 189 | repository = ImagineRepositoryImpl(stringUtils, apiService) 190 | val apiResponse = MockTestUtil.createSearchPhotosResponse() 191 | val apiCall = successCall(apiResponse) 192 | 193 | // When 194 | coEvery { apiService.searchPhotos(any(), any(), any()) } 195 | .returns(apiCall) 196 | 197 | // Invoke 198 | val apiResponseFlow = repository.searchPhotos("", 1, 1) 199 | 200 | // Then 201 | MatcherAssert.assertThat(apiResponseFlow, CoreMatchers.notNullValue()) 202 | 203 | val photosListDataState = apiResponseFlow.first() 204 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.notNullValue()) 205 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.instanceOf(DataState.Success::class.java)) 206 | 207 | val photosList = (photosListDataState as DataState.Success).data 208 | MatcherAssert.assertThat(photosList, CoreMatchers.notNullValue()) 209 | MatcherAssert.assertThat(photosList.size, CoreMatchers.`is`(apiResponse.photosList.size)) 210 | 211 | coVerify(exactly = 1) { apiService.searchPhotos(any(), any(), any()) } 212 | confirmVerified(apiService) 213 | } 214 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/usecases/FetchPopularPhotosUsecaseTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.usecases 2 | 3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule 4 | import com.wajahatkarim3.imagine.MainCoroutinesRule 5 | import com.wajahatkarim3.imagine.data.DataState 6 | import com.wajahatkarim3.imagine.data.repository.ImagineRepository 7 | import io.mockk.MockKAnnotations 8 | import io.mockk.coEvery 9 | import io.mockk.impl.annotations.MockK 10 | import kotlinx.coroutines.flow.first 11 | import kotlinx.coroutines.flow.flowOf 12 | import kotlinx.coroutines.runBlocking 13 | import org.hamcrest.CoreMatchers 14 | import org.hamcrest.CoreMatchers.`is` 15 | import org.hamcrest.MatcherAssert 16 | import org.junit.Assert.* 17 | import org.junit.Before 18 | import org.junit.Rule 19 | import org.junit.Test 20 | import org.junit.runner.RunWith 21 | import org.junit.runners.JUnit4 22 | 23 | @RunWith(JUnit4::class) 24 | class FetchPopularPhotosUsecaseTest { 25 | 26 | @MockK 27 | private lateinit var repository: ImagineRepository 28 | 29 | @Before 30 | fun setUp() { 31 | MockKAnnotations.init(this) 32 | } 33 | 34 | @Test 35 | fun `test invoking FetchPopularPhotosUsecase gives list of photos`() = runBlocking { 36 | // Given 37 | val usecase = FetchPopularPhotosUsecase(repository) 38 | val givenPhotos = MockTestUtil.createPhotos(3) 39 | 40 | // When 41 | coEvery {repository.loadPhotos(any(), any(), any())} 42 | .returns(flowOf(DataState.success(givenPhotos))) 43 | 44 | // Invoke 45 | val photosListFlow = usecase(1, 1, "") 46 | 47 | // Then 48 | MatcherAssert.assertThat(photosListFlow, CoreMatchers.notNullValue()) 49 | 50 | val photosListDataState = photosListFlow.first() 51 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.notNullValue()) 52 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.instanceOf(DataState.Success::class.java)) 53 | 54 | val photosList = (photosListDataState as DataState.Success).data 55 | MatcherAssert.assertThat(photosList, CoreMatchers.notNullValue()) 56 | MatcherAssert.assertThat(photosList.size, `is`(givenPhotos.size)) 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/data/usecases/SearchPhotosUsecaseTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.data.usecases 2 | 3 | import com.wajahatkarim3.imagine.data.DataState 4 | import com.wajahatkarim3.imagine.data.repository.ImagineRepository 5 | import io.mockk.MockKAnnotations 6 | import io.mockk.coEvery 7 | import io.mockk.impl.annotations.MockK 8 | import kotlinx.coroutines.flow.first 9 | import kotlinx.coroutines.flow.flowOf 10 | import kotlinx.coroutines.runBlocking 11 | import org.hamcrest.CoreMatchers 12 | import org.hamcrest.MatcherAssert 13 | import org.junit.Before 14 | 15 | import org.junit.Assert.* 16 | import org.junit.Test 17 | import org.junit.runner.RunWith 18 | import org.junit.runners.JUnit4 19 | 20 | @RunWith(JUnit4::class) 21 | class SearchPhotosUsecaseTest { 22 | 23 | @MockK 24 | private lateinit var repository: ImagineRepository 25 | 26 | @Before 27 | fun setUp() { 28 | MockKAnnotations.init(this) 29 | } 30 | 31 | @Test 32 | fun `test invoking SearchPhotosUsecase gives list of photos`() = runBlocking { 33 | // Given 34 | val usecase = SearchPhotosUsecase(repository) 35 | val givenPhotos = MockTestUtil.createPhotos(3) 36 | 37 | // When 38 | coEvery {repository.searchPhotos(any(), any(), any())} 39 | .returns(flowOf(DataState.success(givenPhotos))) 40 | 41 | // Invoke 42 | val photosListFlow = usecase("", 1, 1) 43 | 44 | // Then 45 | MatcherAssert.assertThat(photosListFlow, CoreMatchers.notNullValue()) 46 | 47 | val photosListDataState = photosListFlow.first() 48 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.notNullValue()) 49 | MatcherAssert.assertThat(photosListDataState, CoreMatchers.instanceOf(DataState.Success::class.java)) 50 | 51 | val photosList = (photosListDataState as DataState.Success).data 52 | MatcherAssert.assertThat(photosList, CoreMatchers.notNullValue()) 53 | MatcherAssert.assertThat(photosList.size, CoreMatchers.`is`(givenPhotos.size)) 54 | } 55 | } -------------------------------------------------------------------------------- /app/src/test/java/com/wajahatkarim3/imagine/ui/home/HomeViewModelTest.kt: -------------------------------------------------------------------------------- 1 | package com.wajahatkarim3.imagine.ui.home 2 | 3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule 4 | import androidx.lifecycle.Observer 5 | import com.wajahatkarim3.imagine.MainCoroutinesRule 6 | import com.wajahatkarim3.imagine.data.DataState 7 | import com.wajahatkarim3.imagine.data.usecases.FetchPopularPhotosUsecase 8 | import com.wajahatkarim3.imagine.data.usecases.SearchPhotosUsecase 9 | import com.wajahatkarim3.imagine.model.PhotoModel 10 | import io.mockk.* 11 | import io.mockk.impl.annotations.MockK 12 | import kotlinx.coroutines.flow.flowOf 13 | import kotlinx.coroutines.runBlocking 14 | import org.junit.After 15 | import org.junit.Before 16 | 17 | import org.junit.Assert.* 18 | import org.junit.Rule 19 | import org.junit.Test 20 | import org.junit.runner.RunWith 21 | import org.junit.runners.JUnit4 22 | 23 | @RunWith(JUnit4::class) 24 | class HomeViewModelTest { 25 | 26 | // Subject under test 27 | private lateinit var viewModel: HomeViewModel 28 | 29 | @get:Rule 30 | var instantExecutorRule = InstantTaskExecutorRule() 31 | 32 | @get:Rule 33 | var coroutinesRule = MainCoroutinesRule() 34 | 35 | @MockK 36 | lateinit var searchPhotosUsecase: SearchPhotosUsecase 37 | 38 | @MockK 39 | lateinit var fetchPopularPhotosUsecase: FetchPopularPhotosUsecase 40 | 41 | @Before 42 | fun setUp() { 43 | MockKAnnotations.init(this) 44 | } 45 | 46 | @After 47 | fun tearDown() { 48 | } 49 | 50 | @Test 51 | fun `test when HomeViewModel is initialized, popular photos are fetched`() = runBlocking { 52 | // Given 53 | val givenPhotos = MockTestUtil.createPhotos(3) 54 | val uiObserver = mockk>(relaxed = true) 55 | val photosListObserver = mockk>>(relaxed = true) 56 | 57 | // When 58 | coEvery { fetchPopularPhotosUsecase.invoke(any(), any(), any()) } 59 | .returns(flowOf(DataState.success(givenPhotos))) 60 | 61 | // Invoke 62 | viewModel = HomeViewModel(fetchPopularPhotosUsecase, searchPhotosUsecase) 63 | viewModel.uiStateLiveData.observeForever(uiObserver) 64 | viewModel.photosListLiveData.observeForever(photosListObserver) 65 | 66 | // Then 67 | coVerify(exactly = 1) { fetchPopularPhotosUsecase.invoke() } 68 | verify { uiObserver.onChanged(match { it == ContentState }) } 69 | verify { photosListObserver.onChanged(match { it.size == givenPhotos.size }) } 70 | } 71 | } -------------------------------------------------------------------------------- /app/src/test/resources/api-response/photos_list_response.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "LBI7cgq3pbM", 4 | "created_at": "2016-05-03T11:00:28-04:00", 5 | "updated_at": "2016-07-10T11:00:01-05:00", 6 | "width": 5245, 7 | "height": 3497, 8 | "color": "#60544D", 9 | "blur_hash": "LoC%a7IoIVxZ_NM|M{s:%hRjWAo0", 10 | "likes": 12, 11 | "liked_by_user": false, 12 | "description": "A man drinking a coffee.", 13 | "user": { 14 | "id": "pXhwzz1JtQU", 15 | "username": "poorkane", 16 | "name": "Gilbert Kane", 17 | "portfolio_url": "https://theylooklikeeggsorsomething.com/", 18 | "bio": "XO", 19 | "location": "Way out there", 20 | "total_likes": 5, 21 | "total_photos": 74, 22 | "total_collections": 52, 23 | "instagram_username": "instantgrammer", 24 | "twitter_username": "crew", 25 | "profile_image": { 26 | "small": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=32&w=32", 27 | "medium": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=64&w=64", 28 | "large": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=128&w=128" 29 | }, 30 | "links": { 31 | "self": "https://api.unsplash.com/users/poorkane", 32 | "html": "https://unsplash.com/poorkane", 33 | "photos": "https://api.unsplash.com/users/poorkane/photos", 34 | "likes": "https://api.unsplash.com/users/poorkane/likes", 35 | "portfolio": "https://api.unsplash.com/users/poorkane/portfolio" 36 | } 37 | }, 38 | "current_user_collections": [ 39 | { 40 | "id": 206, 41 | "title": "Makers: Cat and Ben", 42 | "published_at": "2016-01-12T18:16:09-05:00", 43 | "last_collected_at": "2016-06-02T13:10:03-04:00", 44 | "updated_at": "2016-07-10T11:00:01-05:00", 45 | "cover_photo": null, 46 | "user": null 47 | } 48 | ], 49 | "urls": { 50 | "raw": "https://images.unsplash.com/face-springmorning.jpg", 51 | "full": "https://images.unsplash.com/face-springmorning.jpg?q=75&fm=jpg", 52 | "regular": "https://images.unsplash.com/face-springmorning.jpg?q=75&fm=jpg&w=1080&fit=max", 53 | "small": "https://images.unsplash.com/face-springmorning.jpg?q=75&fm=jpg&w=400&fit=max", 54 | "thumb": "https://images.unsplash.com/face-springmorning.jpg?q=75&fm=jpg&w=200&fit=max" 55 | }, 56 | "links": { 57 | "self": "https://api.unsplash.com/photos/LBI7cgq3pbM", 58 | "html": "https://unsplash.com/photos/LBI7cgq3pbM", 59 | "download": "https://unsplash.com/photos/LBI7cgq3pbM/download", 60 | "download_location": "https://api.unsplash.com/photos/LBI7cgq3pbM/download" 61 | } 62 | } 63 | ] 64 | -------------------------------------------------------------------------------- /app/src/test/resources/api-response/search_photos_response.json: -------------------------------------------------------------------------------- 1 | { 2 | "total": 133, 3 | "total_pages": 7, 4 | "results": [ 5 | { 6 | "id": "eOLpJytrbsQ", 7 | "created_at": "2014-11-18T14:35:36-05:00", 8 | "width": 4000, 9 | "height": 3000, 10 | "color": "#A7A2A1", 11 | "blur_hash": "LaLXMa9Fx[D%~q%MtQM|kDRjtRIU", 12 | "likes": 286, 13 | "liked_by_user": false, 14 | "description": "A man drinking a coffee.", 15 | "user": { 16 | "id": "Ul0QVz12Goo", 17 | "username": "ugmonk", 18 | "name": "Jeff Sheldon", 19 | "first_name": "Jeff", 20 | "last_name": "Sheldon", 21 | "instagram_username": "instantgrammer", 22 | "twitter_username": "ugmonk", 23 | "portfolio_url": "http://ugmonk.com/", 24 | "profile_image": { 25 | "small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41", 26 | "medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f", 27 | "large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202" 28 | }, 29 | "links": { 30 | "self": "https://api.unsplash.com/users/ugmonk", 31 | "html": "http://unsplash.com/@ugmonk", 32 | "photos": "https://api.unsplash.com/users/ugmonk/photos", 33 | "likes": "https://api.unsplash.com/users/ugmonk/likes" 34 | } 35 | }, 36 | "current_user_collections": [], 37 | "urls": { 38 | "raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f", 39 | "full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f", 40 | "regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515", 41 | "small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb", 42 | "thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef" 43 | }, 44 | "links": { 45 | "self": "https://api.unsplash.com/photos/eOLpJytrbsQ", 46 | "html": "http://unsplash.com/photos/eOLpJytrbsQ", 47 | "download": "http://unsplash.com/photos/eOLpJytrbsQ/download" 48 | } 49 | } 50 | ] 51 | } 52 | 53 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | ext { 4 | kotlin_version = '1.4.21' 5 | lifecycle_version = "2.2.0" 6 | appcompat_version = "1.2.0" 7 | constraint_layout_version = "2.0.4" 8 | material_version = "1.2.1" 9 | nav_version = "2.3.1" 10 | dagger_version = "2.30.1" 11 | retrofit_version = "2.9.0" 12 | coroutines_version = "1.3.5" 13 | gson_version = "2.8.6" 14 | okhttp_version = "4.9.0" 15 | } 16 | 17 | repositories { 18 | google() 19 | maven { url "https://www.jitpack.io" } 20 | jcenter() 21 | } 22 | dependencies { 23 | classpath "com.android.tools.build:gradle:4.1.1" 24 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 25 | 26 | // NOTE: Do not place your application dependencies here; they belong 27 | // in the individual module build.gradle files 28 | } 29 | } 30 | 31 | allprojects { 32 | repositories { 33 | google() 34 | maven { url "https://www.jitpack.io" } 35 | jcenter() 36 | } 37 | } 38 | 39 | task clean(type: Delete) { 40 | delete rootProject.buildDir 41 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jan 22 18:26:37 PKT 2021 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-6.5-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /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 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 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 Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /screenshots/Imagine-UnitTests.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/Imagine-UnitTests.PNG -------------------------------------------------------------------------------- /screenshots/PhotoDetailsDay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/PhotoDetailsDay.png -------------------------------------------------------------------------------- /screenshots/PhotoDetailsNight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/PhotoDetailsNight.png -------------------------------------------------------------------------------- /screenshots/PopularPhotosDay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/PopularPhotosDay.png -------------------------------------------------------------------------------- /screenshots/PopularPhotosNight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/PopularPhotosNight.png -------------------------------------------------------------------------------- /screenshots/SearchResultsDay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/SearchResultsDay.png -------------------------------------------------------------------------------- /screenshots/SearchResultsNight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wajahatkarim3/Android-Github-Actions/de030d357fabdd0b47dfd17041fa743361245369/screenshots/SearchResultsNight.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | rootProject.name = "Images" --------------------------------------------------------------------------------