├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── configuration.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── task │ │ └── ui │ │ └── component │ │ └── news │ │ └── HomeActivityTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── task │ │ │ ├── App.kt │ │ │ ├── data │ │ │ ├── DataRepository.kt │ │ │ ├── DataSource.kt │ │ │ ├── local │ │ │ │ └── LocalRepository.kt │ │ │ └── remote │ │ │ │ ├── RemoteRepository.kt │ │ │ │ ├── RemoteSource.kt │ │ │ │ ├── ServiceError.kt │ │ │ │ ├── ServiceGenerator.kt │ │ │ │ ├── ServiceResponse.kt │ │ │ │ ├── dto │ │ │ │ ├── Multimedia.kt │ │ │ │ ├── NewsItem.kt │ │ │ │ └── NewsModel.kt │ │ │ │ └── service │ │ │ │ └── NewsService.kt │ │ │ ├── di │ │ │ ├── MainComponent.kt │ │ │ └── MainModule.kt │ │ │ ├── ui │ │ │ ├── base │ │ │ │ ├── BaseActivity.kt │ │ │ │ ├── BaseFragment.kt │ │ │ │ ├── Presenter.kt │ │ │ │ └── listeners │ │ │ │ │ ├── ActionBarView.kt │ │ │ │ │ ├── BaseCallback.kt │ │ │ │ │ ├── BaseView.kt │ │ │ │ │ └── RecyclerItemListener.kt │ │ │ └── component │ │ │ │ ├── details │ │ │ │ ├── DetailsActivity.kt │ │ │ │ ├── DetailsContract.kt │ │ │ │ └── DetailsPresenter.kt │ │ │ │ ├── news │ │ │ │ ├── HomeActivity.kt │ │ │ │ ├── HomeContract.kt │ │ │ │ ├── HomePresenter.kt │ │ │ │ ├── NewsAdapter.kt │ │ │ │ └── NewsViewHolder.kt │ │ │ │ └── splash │ │ │ │ ├── SplashActivity.kt │ │ │ │ ├── SplashContract.kt │ │ │ │ └── SplashPresenter.kt │ │ │ ├── usecase │ │ │ ├── NewsUseCase.kt │ │ │ └── UseCase.kt │ │ │ └── utils │ │ │ ├── Constants.kt │ │ │ ├── EspressoIdlingResource.kt │ │ │ ├── L.kt │ │ │ ├── Network.kt │ │ │ ├── ObjectUtil.kt │ │ │ └── SimpleCountingIdlingResource.kt │ └── res │ │ ├── drawable-hdpi │ │ └── news.png │ │ ├── drawable-mdpi │ │ └── news.png │ │ ├── drawable-xhdpi │ │ └── news.png │ │ ├── drawable-xxhdpi │ │ └── news.png │ │ ├── drawable-xxxhdpi │ │ └── news.png │ │ ├── drawable │ │ └── border.xml │ │ ├── layout │ │ ├── details_layout.xml │ │ ├── home_activity.xml │ │ ├── news_item.xml │ │ ├── splash_layout.xml │ │ └── toolbar.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── task │ └── ui │ └── component │ └── news │ ├── HomePresenterTest.kt │ ├── NewsUseCaseTest.kt │ └── TestModelsGenerator.kt ├── build.gradle ├── googlec49bc29aa25b1e6d.html ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── readme-images ├── 8399.png ├── android-mvp-flow.png └── androkotlin.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /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 2014 The Android Open Source Project 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Model–view–presenter (MVP)](https://github.com/ahmedeltaher/Android-MVP-Architecture) 2 | 3 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-android--best--practices-brightgreen.svg?style=flat)](https://android-arsenal.com/details/3/4975) [![kotlin](https://img.shields.io/badge/Kotlin-1.3.xxx-brightgreen.svg)](https://kotlinlang.org/) [![coroutines](https://img.shields.io/badge/coroutines-asynchronous-red.svg)](https://kotlinlang.org/docs/reference/coroutines-overview.html) [![ANKO](https://img.shields.io/badge/Anko-commons-blue.svg)](https://github.com/Kotlin/anko) [![Mockk](https://img.shields.io/badge/Mockk-testing-yellow.svg)](https://mockk.io/) [![Junit5](https://img.shields.io/badge/Junit5-testing-yellowgreen.svg)](https://junit.org/junit5/) [![Espresso](https://img.shields.io/badge/Espresso-testing-lightgrey.svg)](https://developer.android.com/training/testing/espresso/) [![Dagger 2](https://img.shields.io/badge/Dagger-2.xx-orange.svg)](https://google.github.io/dagger/) [![Kotlin-Android-Extensions ](https://img.shields.io/badge/Kotlin--Android--Extensions-plugin-red.svg)](https://kotlinlang.org/docs/tutorials/android-plugin.html) [![MVVM ](https://img.shields.io/badge/Clean--Code-MVVM-brightgreen.svg)](https://github.com/googlesamples/android-architecture) ![MVP ](https://img.shields.io/badge/Clean--Code-MVP-brightgreen.svg) 4 | 5 | 6 | ![androkotlin](https://user-images.githubusercontent.com/1812129/68315997-facddf80-00b8-11ea-81f7-64980da690f1.png)![android-mvp-flow](https://user-images.githubusercontent.com/1812129/68316088-1e912580-00b9-11ea-9a1d-717afa920318.png) 7 | 8 | Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern which mostly used for building user interfaces. In MVP, the presenter assumes the functionality of the “middle-man”. In MVP, all presentation logic is pushed to the presenter. 9 | Check here for [MVVM](https://github.com/ahmedeltaher/Android-MVVM-architecture) 10 | 11 | **What is Coroutines ?** 12 | ------------------- 13 | **Coroutines :** 14 | Is light wight threads for asynchronous programming, Coroutines not only open the doors to 15 | asynchronous programming, but also provide a wealth of other possibilities such as concurrency, actors, etc. 16 | 17 | **Coroutines VS RXJava** 18 | ------------------- 19 | They're different tools with different strengths. Like a tank and a cannon, they have a lot of overlap but are more or less desirable under different circumstances. 20 | - Coroutines Is light wight threads for asynchronous programming. 21 | - RX-Kotlin/RX-Java is functional reactive programming, its core pattern relay on 22 | observer design pattern, so you can use it to handle user interaction with UI while you 23 | still using coroutines as main core for background work. 24 | 25 | **How does Coroutines concept work ?** 26 | ------------ 27 | - Kotlin coroutine is a way of doing things asynchronously in a sequential manner. Creating a coroutine is a lot cheaper vs creating a thread. 28 | 29 | 30 | **When I can choose Coroutines or RX-Kotlin to do some behaviour ?** 31 | -------------------------- 32 | - Coroutines : *When we have concurrent tasks , like you would fetch data from Remote connections 33 | , database , any background processes , sure you can use RX in such cases too, but it looks like 34 | you use a tank to kill ant.* 35 | - RX-Kotlin : *When you would to handle stream of UI actions like : user scrolling , clicks , 36 | update UI upon some events .....ect .* 37 | 38 | 39 | **What is the Coroutines benefits?** 40 | ----------------------------- 41 | 42 | - Writing an asynchronous code is sequential manner. 43 | - Costing of create coroutines are much cheaper to crate threads. 44 | - Don't be over engineered to use observable pattern, when no need to use it. 45 | - parent coroutine can automatically manage the life cycle of its child coroutines for you. 46 | 47 | 48 | **Handle Retrofit with Coroutines** 49 | ----------------------------- 50 | ![8399](https://user-images.githubusercontent.com/1812129/68318999-e93b0680-00bd-11ea-9d76-058222c7a654.png) 51 | 52 | - Add Coroutines to your gradle file 53 | 54 | > // Add Coroutines 55 | > implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' 56 | > implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2' 57 | > implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.2' 58 | > // Add Retrofit2 59 | > implementation 'com.squareup.retrofit2:retrofit:2.6.2' 60 | > implementation 'com.squareup.retrofit2:converter-gson:2.6.2' 61 | > implementation 'com.squareup.okhttp3:okhttp:4.2.2' 62 | 63 | 64 | - Make Retrofit Calls. 65 | 66 | > @GET("topstories/v2/home.json") 67 | > fun fetchNews(): Call 68 | 69 | 70 | - With ```async``` we create new coroutine and returns its future result as an implementation of [Deferred]. 71 | - The coroutine builder called ```launch``` allow us to start a coroutine in background and keep working in the meantime. 72 | - so async will run in background then return its promised result to parent coroutine which 73 | created by launch. 74 | - when we get a result, it is up to us to do handle the result. 75 | 76 | 77 | 78 | 79 | 80 | > launch { 81 | > try { 82 | > val serviceResponse: Data? = withContext(Dispatchers.IO) { dataRepository.requestNews() 83 | > } 84 | > if (serviceResponse?.code == Error.SUCCESS_CODE) { 85 | > val data = serviceResponse.data 86 | > callback.onSuccess(data as NewsModel) 87 | > } else { 88 | > callback.onFail(serviceResponse?.error) 89 | > } 90 | > } catch (e: Exception) { 91 | > callback.onFail(Error(e)) 92 | > } 93 | > } 94 | 95 | 96 | **Keep your code clean according to MVP** 97 | ----------------------------- 98 | - yes , RXAndroid is easy , powerful , but you should know in which MVP 99 | layer you will put it . 100 | - for observables which will emit data stream , it has to be in your 101 | data layer , and don't inform those observables any thing else like 102 | in which thread those will consume , cause it is another 103 | responsibility , and according to `Single responsibility principle` 104 | in `SOLID (object-oriented design)` , so don't break this concept by 105 | mixing every thing due to RXAndroid ease . 106 | 107 | 108 | ![MVP](https://user-images.githubusercontent.com/1812129/68315449-14baf280-00b8-11ea-99ff-8dcfc4dfdcd3.jpg) 109 | 110 | 111 | 112 | ---------- 113 | **LICENSE** 114 | ------------------- 115 | 116 | 117 | Copyright [2016] [Ahmed Eltaher] 118 | 119 | Licensed under the Apache License, Version 2.0 (the "License"); 120 | you may not use this file except in compliance with the License. 121 | You may obtain a copy of the License at 122 | 123 | http://www.apache.org/licenses/LICENSE-2.0 124 | Unless required by applicable law or agreed to in writing, software 125 | distributed under the License is distributed on an "AS IS" BASIS, 126 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 127 | See the License for the specific language governing permissions and 128 | limitations under the License. -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-kapt' 6 | 7 | apply plugin: 'kotlin-android-extensions' 8 | 9 | apply plugin: 'kotlin-platform-android' 10 | 11 | //ButterKnife 12 | apply plugin: 'com.jakewharton.butterknife' 13 | 14 | apply from: 'configuration.gradle' 15 | 16 | android { 17 | compileSdkVersion 29 18 | buildToolsVersion '29.0.2' 19 | defaultConfig { 20 | applicationId 'com.eltaher.task' 21 | minSdkVersion 16 22 | targetSdkVersion 29 23 | versionCode project.versionCode 24 | versionName project.versionName 25 | multiDexEnabled true 26 | } 27 | buildTypes { 28 | debug { 29 | debuggable true 30 | } 31 | release { 32 | debuggable false 33 | minifyEnabled false 34 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 35 | } 36 | } 37 | 38 | compileOptions { 39 | targetCompatibility JavaVersion.VERSION_1_8 40 | sourceCompatibility JavaVersion.VERSION_1_8 41 | } 42 | productFlavors { 43 | } 44 | defaultConfig { 45 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 46 | } 47 | kotlinOptions { 48 | jvmTarget = JavaVersion.VERSION_1_8 49 | } 50 | packagingOptions { 51 | pickFirst 'META-INF/kotlinx-io.kotlin_module' 52 | pickFirst 'META-INF/atomicfu.kotlin_module' 53 | pickFirst 'META-INF/kotlinx-coroutines-core.kotlin_module' 54 | pickFirst 'META-INF/kotlinx-coroutines-io.kotlin_module' 55 | } 56 | 57 | } 58 | repositories { 59 | repositories { 60 | mavenCentral() 61 | } 62 | } 63 | configurations.all { 64 | resolutionStrategy { 65 | force "com.android.support:support-annotations:28.0.0" 66 | exclude module: "support-v13" 67 | } 68 | } 69 | dependencies { 70 | implementation fileTree(include: ['*.jar'], dir: 'libs') 71 | 72 | //kotlin 73 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 74 | implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" 75 | 76 | /**-------------------testing libs------------------------------------------**/ 77 | 78 | //UI Testing , AndroidJUnitRunner and JUnit Rules &Espresso dependencies 79 | 80 | //junit 5 81 | testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.5.2' 82 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2' 83 | testImplementation 'org.junit.platform:junit-platform-runner:1.5.2' 84 | 85 | //noinspection GradleCompatible 86 | implementation 'androidx.test:rules:1.2.0' 87 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 88 | androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0' 89 | androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0' 90 | androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0' 91 | androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0' 92 | androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0' 93 | androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' 94 | implementation 'androidx.test.espresso:espresso-core:3.2.0' 95 | implementation 'androidx.test.espresso:espresso-contrib:3.2.0' 96 | implementation 'androidx.test.espresso:espresso-intents:3.2.0' 97 | implementation 'androidx.test.espresso:espresso-accessibility:3.2.0' 98 | implementation 'androidx.test.espresso:espresso-web:3.2.0' 99 | implementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0' 100 | implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' 101 | 102 | /**-------------------------------------------------------------**/ 103 | 104 | //android support & recyclerview 105 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 106 | implementation 'androidx.recyclerview:recyclerview:1.0.0' 107 | implementation 'androidx.appcompat:appcompat:1.1.0' 108 | implementation 'com.google.android.material:material:1.2.0-alpha01' 109 | 110 | //Dagger 111 | implementation 'com.google.dagger:dagger:2.25.2' 112 | kapt 'com.google.dagger:dagger-compiler:2.25.2' 113 | 114 | //butterknife 115 | implementation 'com.jakewharton:butterknife:10.2.0' 116 | kapt 'com.jakewharton:butterknife-compiler:10.2.0' 117 | 118 | //Logging 119 | implementation 'com.squareup.okhttp3:logging-interceptor:4.2.2' 120 | 121 | // retrofit 122 | implementation 'com.squareup.retrofit2:retrofit:2.6.2' 123 | implementation 'com.squareup.retrofit2:converter-gson:2.6.2' 124 | implementation 'com.squareup.okhttp3:okhttp:4.2.2' 125 | 126 | //picasso 127 | implementation 'com.squareup.picasso:picasso:2.71828' 128 | 129 | //MultiDex 130 | implementation 'androidx.multidex:multidex:2.0.1' 131 | 132 | //ANKO 133 | implementation "org.jetbrains.anko:anko-commons:$anko_version" 134 | implementation "org.jetbrains.anko:anko-design:$anko_version" 135 | androidExtensions { 136 | experimental = true 137 | } 138 | //Mockk 139 | implementation 'io.mockk:mockk:1.9.3' 140 | //coroutines 141 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' 142 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2' 143 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.2' 144 | } -------------------------------------------------------------------------------- /app/configuration.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | //App name 3 | versionCode = 1 4 | versionName = "1.0" 5 | 6 | //Compilation 7 | minSdkVersion = 16 8 | compileSdkVersion = 28 9 | targetSdkVersion = 28 10 | 11 | //Libraries 12 | buildToolsVersion = '28.0.0' 13 | supportLibraryVersion = '28.0.0' 14 | daggerVersion = '2.0.2' 15 | parcelablepleaseVersion = '1.0.2' 16 | espressoVersion = '2.2.2' 17 | retrofitVersion = '2.2.0' 18 | okhttpVersion = '3.3.0' 19 | butterKnifeVersion = '8.5.1' 20 | mockitoVersion = '2.7.1' 21 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/wkda/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/task/ui/component/news/HomeActivityTest.java: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news; 2 | 3 | 4 | import com.task.App; 5 | import com.task.R; 6 | 7 | import org.hamcrest.Matchers; 8 | import org.junit.After; 9 | import org.junit.Before; 10 | import org.junit.Rule; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | 14 | import androidx.test.espresso.Espresso; 15 | import androidx.test.espresso.IdlingResource; 16 | import androidx.test.espresso.ViewInteraction; 17 | import androidx.test.espresso.action.ViewActions; 18 | import androidx.test.espresso.contrib.RecyclerViewActions; 19 | import androidx.test.espresso.matcher.ViewMatchers; 20 | import androidx.test.rule.ActivityTestRule; 21 | import androidx.test.runner.AndroidJUnit4; 22 | 23 | import static androidx.test.espresso.Espresso.onView; 24 | import static androidx.test.espresso.Espresso.pressBack; 25 | import static androidx.test.espresso.action.ViewActions.click; 26 | import static androidx.test.espresso.action.ViewActions.pressImeActionButton; 27 | import static androidx.test.espresso.action.ViewActions.scrollTo; 28 | import static androidx.test.espresso.assertion.ViewAssertions.matches; 29 | import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; 30 | import static androidx.test.espresso.matcher.ViewMatchers.withId; 31 | import static androidx.test.espresso.matcher.ViewMatchers.withText; 32 | import static org.hamcrest.Matchers.not; 33 | 34 | @RunWith(AndroidJUnit4.class) 35 | public class HomeActivityTest { 36 | private final String testSearchString = "the"; 37 | 38 | @Rule 39 | public ActivityTestRule mActivityTestRule = new ActivityTestRule<>(HomeActivity.class); 40 | 41 | private IdlingResource mIdlingResource; 42 | 43 | @Before 44 | public void setup () { 45 | mIdlingResource = mActivityTestRule.getActivity().getCountingIdlingResource(); 46 | Espresso.registerIdlingResources(mIdlingResource); 47 | } 48 | 49 | @Test 50 | public void testSearch () { 51 | ViewInteraction searchEditText = onView(withId(R.id.et_search)); 52 | searchEditText.perform(click()); 53 | searchEditText.perform(ViewActions.typeText(testSearchString), pressImeActionButton()); 54 | onView(withId(R.id.btn_search)).perform(click()); 55 | onView(withId(R.id.tv_title)).check(matches(isDisplayed())); 56 | onView(withId(R.id.tv_description)).perform(scrollTo()); 57 | onView(withId(R.id.tv_description)).check(matches(isDisplayed())); 58 | pressBack(); 59 | searchEditText.check(matches(withText(testSearchString))); 60 | onView(withId(R.id.rv_news_list)).check(matches(isDisplayed())); 61 | } 62 | 63 | @Test 64 | public void testScroll () { 65 | onView(ViewMatchers.withId(R.id.rv_news_list)) 66 | .perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); 67 | onView(withId(R.id.tv_title)).check(matches(isDisplayed())); 68 | onView(withId(R.id.tv_description)).check(matches(isDisplayed())); 69 | } 70 | 71 | @Test 72 | public void testRefresh () { 73 | //Before refresh there is a list . 74 | onView(withId(R.id.rv_news_list)).check(matches(isDisplayed())); 75 | onView(withId(R.id.pb_loading)).check(matches((not(isDisplayed())))); 76 | // do refresh . 77 | onView(withId(R.id.ic_toolbar_refresh)).perform(click()); 78 | //after refresh there is a list. 79 | onView(withId(R.id.rv_news_list)).check(matches(isDisplayed())); 80 | onView(withId(R.id.pb_loading)).check(matches((not(isDisplayed())))); 81 | } 82 | 83 | @Test 84 | public void displayNewsData () { 85 | onView(withId(R.id.rv_news_list)).check(matches(isDisplayed())); 86 | onView(withId(R.id.pb_loading)).check(matches((not(isDisplayed())))); 87 | } 88 | 89 | @Test 90 | public void searchIsActive () { 91 | onView(withId(R.id.rl_search)).check(matches(isDisplayed())); 92 | onView(withId(R.id.et_search)).check(matches(isDisplayed())); 93 | onView(withId(R.id.btn_search)).check(matches(isDisplayed())); 94 | } 95 | 96 | @After 97 | public void unregisterIdlingResource () { 98 | if (mIdlingResource != null) { 99 | Espresso.unregisterIdlingResources(mIdlingResource); 100 | } 101 | } 102 | 103 | public void testEmptySearch () { 104 | String testSearchString = ""; 105 | ViewInteraction searchEditText = onView(withId(R.id.et_search)); 106 | searchEditText.perform(click()); 107 | searchEditText.perform(ViewActions.typeText(testSearchString), pressImeActionButton()); 108 | onView(withId(R.id.btn_search)).perform(click()); 109 | onView(Matchers.allOf(withId(R.id.snackbar_text), withText(App.context.getString(R.string.search_error)))).check(matches(isDisplayed())); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/App.kt: -------------------------------------------------------------------------------- 1 | package com.task 2 | 3 | import android.annotation.SuppressLint 4 | import android.content.Context 5 | import android.graphics.drawable.Drawable 6 | import android.os.Build 7 | import androidx.annotation.VisibleForTesting 8 | import androidx.multidex.MultiDexApplication 9 | import com.task.di.DaggerMainComponent 10 | import com.task.di.MainComponent 11 | 12 | /** 13 | * Created by AhmedEltaher on 5/12/2016 14 | */ 15 | 16 | class App : MultiDexApplication() { 17 | var mainComponent: MainComponent? = null 18 | private set 19 | 20 | override fun onCreate() { 21 | super.onCreate() 22 | mainComponent = DaggerMainComponent.create() 23 | context = applicationContext 24 | } 25 | 26 | @VisibleForTesting 27 | fun setComponent(mainComponent: MainComponent) { 28 | this.mainComponent = mainComponent 29 | } 30 | 31 | companion object { 32 | @SuppressLint("StaticFieldLeak") 33 | lateinit var context: Context 34 | fun getDrawableById(resId: Int): Drawable { 35 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 36 | context.resources.getDrawable(resId,context.theme) 37 | else 38 | context.resources.getDrawable(resId) 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/DataRepository.kt: -------------------------------------------------------------------------------- 1 | package com.task.data 2 | 3 | import com.task.data.local.LocalRepository 4 | import com.task.data.remote.RemoteRepository 5 | import com.task.data.remote.ServiceResponse 6 | import javax.inject.Inject 7 | 8 | 9 | /** 10 | * Created by AhmedEltaher on 5/12/2016 11 | */ 12 | 13 | class DataRepository @Inject 14 | constructor(private val remoteRepository: RemoteRepository, private val localRepository: LocalRepository) : DataSource { 15 | 16 | override suspend fun requestNews(): ServiceResponse? { 17 | return remoteRepository.requestNews() 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/DataSource.kt: -------------------------------------------------------------------------------- 1 | package com.task.data 2 | 3 | import com.task.data.remote.ServiceResponse 4 | 5 | /** 6 | * Created by ahmedeltaher on 3/23/17. 7 | */ 8 | 9 | internal interface DataSource { 10 | suspend fun requestNews(): ServiceResponse? 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/local/LocalRepository.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.local 2 | 3 | import javax.inject.Inject 4 | 5 | /** 6 | * Created by AhmedEltaher on 5/12/2016 7 | */ 8 | 9 | class LocalRepository @Inject 10 | constructor() 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/RemoteRepository.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote 2 | 3 | import com.task.App 4 | import com.task.data.remote.service.NewsService 5 | import com.task.utils.Constants 6 | import com.task.utils.Constants.INSTANCE.ERROR_UNDEFINED 7 | import com.task.utils.Network.Utils.isConnected 8 | import retrofit2.Call 9 | import java.io.IOException 10 | import javax.inject.Inject 11 | 12 | 13 | /** 14 | * Created by AhmedEltaher on 5/12/2016 15 | */ 16 | 17 | class RemoteRepository @Inject 18 | constructor(private val serviceGenerator: ServiceGenerator) : RemoteSource { 19 | 20 | override suspend fun requestNews(): ServiceResponse? { 21 | return if (!isConnected(App.context)) { 22 | ServiceResponse(ServiceError(code = -1, description = ServiceError.NETWORK_ERROR)) 23 | } else { 24 | val newsService = serviceGenerator.createService(NewsService::class.java, Constants.BASE_URL) 25 | processCall(newsService.fetchNews(), false) 26 | } 27 | } 28 | 29 | private fun processCall(call: Call<*>, isVoid: Boolean): ServiceResponse { 30 | if (!isConnected(App.context)) { 31 | return ServiceResponse(ServiceError()) 32 | } 33 | try { 34 | val response = call.execute() 35 | ?: return ServiceResponse(ServiceError(ServiceError.NETWORK_ERROR, ERROR_UNDEFINED)) 36 | val responseCode = response.code() 37 | /** 38 | * isVoid is for APIs which reply only with code without any body, such as some Apis 39 | * reply with 200 or 401.... 40 | */ 41 | return if (response.isSuccessful) { 42 | val apiResponse: Any? = if (isVoid) null else response.body() 43 | ServiceResponse(responseCode, apiResponse) 44 | } else { 45 | val serviceError = ServiceError(response.message(), responseCode) 46 | ServiceResponse(serviceError) 47 | } 48 | } catch (e: IOException) { 49 | return ServiceResponse(ServiceError(ServiceError.NETWORK_ERROR, ERROR_UNDEFINED)) 50 | } 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/RemoteSource.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote 2 | 3 | /** 4 | * Created by ahmedEltaher on 3/23/17. 5 | */ 6 | 7 | internal interface RemoteSource { 8 | suspend fun requestNews(): ServiceResponse? 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/ServiceError.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016 5 | */ 6 | 7 | class ServiceError { 8 | var description: String? = "" 9 | var code: Int = -1 10 | 11 | constructor() 12 | 13 | constructor(description: String, code: Int) { 14 | this.description = description 15 | this.code = code 16 | } 17 | 18 | companion object { 19 | const val NETWORK_ERROR = "Unknown ServiceError" 20 | private const val GROUP_200 = 2 21 | private const val GROUP_400 = 4 22 | private const val GROUP_500 = 5 23 | private const val VALUE_100 = 100 24 | const val SUCCESS_CODE = 200 25 | const val ERROR_CODE = 400 26 | 27 | fun isClientError(errorCode: Int): Boolean { 28 | return errorCode / VALUE_100 == GROUP_400 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/ServiceGenerator.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote 2 | 3 | import com.google.gson.Gson 4 | import com.task.BuildConfig 5 | import okhttp3.Interceptor 6 | import okhttp3.OkHttpClient 7 | import okhttp3.logging.HttpLoggingInterceptor 8 | import retrofit2.Retrofit 9 | import retrofit2.converter.gson.GsonConverterFactory 10 | import java.util.concurrent.TimeUnit 11 | import javax.inject.Inject 12 | import javax.inject.Singleton 13 | 14 | /** 15 | * Created by AhmedEltaher on 5/12/2016 16 | */ 17 | 18 | @Singleton 19 | class ServiceGenerator @Inject 20 | constructor(private val gson: Gson) { 21 | 22 | //Network constants 23 | private val TIMEOUT_CONNECT = 30 //In seconds 24 | private val TIMEOUT_READ = 30 //In seconds 25 | private val CONTENT_TYPE = "Content-Type" 26 | private val CONTENT_TYPE_VALUE = "application/json" 27 | 28 | private val okHttpBuilder: OkHttpClient.Builder = OkHttpClient.Builder() 29 | private var retrofit: Retrofit? = null 30 | 31 | private var headerInterceptor = Interceptor { chain -> 32 | val original = chain.request() 33 | 34 | val request = original.newBuilder() 35 | .header(CONTENT_TYPE, CONTENT_TYPE_VALUE) 36 | .method(original.method, original.body) 37 | .build() 38 | 39 | chain.proceed(request) 40 | } 41 | 42 | private val logger: HttpLoggingInterceptor 43 | get() { 44 | val loggingInterceptor = HttpLoggingInterceptor() 45 | if (BuildConfig.DEBUG) { 46 | loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS).level = HttpLoggingInterceptor.Level.BODY 47 | } 48 | return loggingInterceptor 49 | } 50 | 51 | init { 52 | okHttpBuilder.addInterceptor(headerInterceptor) 53 | okHttpBuilder.addInterceptor (logger) 54 | okHttpBuilder.connectTimeout(TIMEOUT_CONNECT.toLong(), TimeUnit.SECONDS) 55 | okHttpBuilder.readTimeout(TIMEOUT_READ.toLong(), TimeUnit.SECONDS) 56 | } 57 | 58 | fun createService(serviceClass: Class, baseUrl: String): S { 59 | val client = okHttpBuilder.build() 60 | retrofit = Retrofit.Builder() 61 | .baseUrl(baseUrl).client(client) 62 | .addConverterFactory(GsonConverterFactory.create(gson)) 63 | .build() 64 | return retrofit!!.create(serviceClass) 65 | } 66 | } -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/ServiceResponse.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016 5 | */ 6 | 7 | class ServiceResponse(var code: Int = -1, var serviceError: ServiceError? = null, var data: Any? = null) { 8 | 9 | constructor(errorCode: Int, response: Any?) : this(errorCode, data = response) 10 | 11 | constructor(error: ServiceError) : this() 12 | 13 | constructor(response: Any) : this(data = response) 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/dto/Multimedia.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote.dto 2 | 3 | import android.os.Parcelable 4 | import com.google.gson.annotations.SerializedName 5 | import kotlinx.android.parcel.Parcelize 6 | 7 | /** 8 | * we define all the variables as @var, because it might happen that backend send some values as 9 | * null 10 | */ 11 | /** 12 | *@Parcelize is from kotlin experimental but it is stable, and we use it for Parcelable 13 | * impersonation 14 | */ 15 | /** 16 | * you can convert your json to kotlin data class in easy simple way, by using 17 | * @(JSON To Kotlin Class) plugin in android studio, you can install the plugin as any other 18 | * plugin and then use it, for more details check here: 19 | * https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass- 20 | */ 21 | @Parcelize 22 | data class Multimedia(@SerializedName("url") var url: String? = null, 23 | @SerializedName("format") var format: String? = null, 24 | @SerializedName("height") var height: Long? = null, 25 | @SerializedName("width") var width: Long? = null, 26 | @SerializedName("type") var type: String? = null, 27 | @SerializedName("subtype") var subtype: String? = null, 28 | @SerializedName("caption") var caption: String? = null, 29 | @SerializedName("copyright") var copyright: String? = null) : Parcelable 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/dto/NewsItem.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote.dto 2 | 3 | import android.os.Parcelable 4 | import com.google.gson.annotations.SerializedName 5 | import kotlinx.android.parcel.Parcelize 6 | /** 7 | * we define all the variables as @var, because it might happen that backend send some values as 8 | * null 9 | */ 10 | /** 11 | *@Parcelize is from kotlin experimental but it is stable, and we use it for Parcelable 12 | * impersonation 13 | */ 14 | /** 15 | * you can convert your json to kotlin data class in easy simple way, by using 16 | * @(JSON To Kotlin Class) plugin in android studio, you can install the plugin as any other 17 | * plugin and then use it, for more details check here: 18 | * https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass- 19 | */ 20 | @Parcelize 21 | data class NewsItem(@SerializedName("section") var section: String? = null, 22 | @SerializedName("subsection") var subsection: String? = null, 23 | @SerializedName("title") var title: String? = null, 24 | @SerializedName("abstract") var abstract: String? = null, 25 | @SerializedName("url") var url: String? = null, 26 | @SerializedName("byline") var byline: String? = null, 27 | @SerializedName("item_type") var itemType: String? = null, 28 | @SerializedName("updated_date") var updatedDate: String? = null, 29 | @SerializedName("created_date") var createdDate: String? = null, 30 | @SerializedName("published_date") var publishedDate: String? = null, 31 | @SerializedName("material_type_facet") var materialTypeFacet: String? = null, 32 | @SerializedName("kicker") var kicker: String? = null, 33 | @SerializedName("des_facet") var desFacet: List? = null, 34 | @SerializedName("org_facet") var orgFacet: List? = null, 35 | @SerializedName("per_facet") var perFacet: List? = null, 36 | @SerializedName("geo_facet") var geoFacet: List? = null, 37 | @SerializedName("multimedia") var multimedia: List? = null, 38 | @SerializedName("short_url") var shortUrl: String? = null) : Parcelable 39 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/dto/NewsModel.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote.dto 2 | 3 | import com.google.gson.annotations.SerializedName 4 | 5 | /** 6 | * we define all the variables as @var, because it might happen that backend send some values as 7 | * null 8 | */ 9 | /** 10 | * you can convert your json to kotlin data class in easy simple way, by using 11 | * @(JSON To Kotlin Class) plugin in android studio, you can install the plugin as any other 12 | * plugin and then use it, for more details check here: 13 | * https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass- 14 | */ 15 | data class NewsModel(@SerializedName("status") var status: String? = null, 16 | @SerializedName("copyright") var copyright: String? = null, 17 | @SerializedName("section") var section: String? = null, 18 | @SerializedName("last_updated") var lastUpdated: String? = null, 19 | @SerializedName("num_results") var numResults: Long? = null, 20 | @SerializedName("results") var newsItems: List? = null) 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/data/remote/service/NewsService.kt: -------------------------------------------------------------------------------- 1 | package com.task.data.remote.service 2 | 3 | import com.task.data.remote.dto.NewsModel 4 | import retrofit2.Call 5 | import retrofit2.http.GET 6 | import retrofit2.http.Query 7 | 8 | /** 9 | * Created by AhmedEltaher on 5/12/2016 10 | */ 11 | 12 | interface NewsService { 13 | @GET("topstories/v2/home.json?api-key=4rfwOLzLTWd1a5xixcPjwddAhw3p0eiF") 14 | fun fetchNews(): Call 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/di/MainComponent.kt: -------------------------------------------------------------------------------- 1 | package com.task.di 2 | 3 | 4 | import com.task.ui.component.details.DetailsActivity 5 | import com.task.ui.component.news.HomeActivity 6 | import com.task.ui.component.splash.SplashActivity 7 | import dagger.Component 8 | import javax.inject.Singleton 9 | 10 | /** 11 | * Created by AhmedEltaher on 5/12/2016 12 | */ 13 | @Singleton 14 | @Component(modules = [MainModule::class]) 15 | interface MainComponent { 16 | fun inject(activity: SplashActivity) 17 | 18 | fun inject(activity: HomeActivity) 19 | 20 | fun inject(activity: DetailsActivity) 21 | } 22 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/di/MainModule.kt: -------------------------------------------------------------------------------- 1 | package com.task.di 2 | 3 | 4 | import com.google.gson.Gson 5 | import com.google.gson.GsonBuilder 6 | import com.task.data.local.LocalRepository 7 | import dagger.Module 8 | import dagger.Provides 9 | import kotlinx.coroutines.Dispatchers 10 | import javax.inject.Singleton 11 | import kotlin.coroutines.CoroutineContext 12 | 13 | /** 14 | * Created by AhmedEltaher on 5/12/2016 15 | */ 16 | 17 | @Module 18 | class MainModule { 19 | @Provides 20 | @Singleton 21 | fun provideLocalRepository(): LocalRepository { 22 | return LocalRepository() 23 | } 24 | 25 | @Provides 26 | @Singleton 27 | fun provideGson(): Gson { 28 | return GsonBuilder().create() 29 | } 30 | 31 | @Provides 32 | @Singleton 33 | fun provideCoroutineContext(): CoroutineContext { 34 | return Dispatchers.Main 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/BaseActivity.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base 2 | 3 | import android.os.Bundle 4 | import android.view.MenuItem 5 | import android.view.View.GONE 6 | import android.view.View.VISIBLE 7 | import android.widget.ImageView 8 | import android.widget.TextView 9 | import androidx.appcompat.app.AppCompatActivity 10 | import androidx.appcompat.widget.Toolbar 11 | import butterknife.BindView 12 | import butterknife.ButterKnife 13 | import butterknife.Unbinder 14 | import com.task.R 15 | import com.task.ui.base.listeners.ActionBarView 16 | import com.task.ui.base.listeners.BaseView 17 | 18 | /** 19 | * Created by AhmedEltaher on 5/12/2016 20 | */ 21 | 22 | 23 | abstract class BaseActivity : AppCompatActivity(), BaseView, ActionBarView { 24 | 25 | protected lateinit var presenter: Presenter<*> 26 | 27 | @JvmField 28 | @BindView(R.id.toolbar) 29 | internal var toolbar: Toolbar? = null 30 | 31 | @JvmField 32 | @BindView(R.id.ic_toolbar_setting) 33 | internal var icSettings: ImageView? = null 34 | 35 | @JvmField 36 | @BindView(R.id.ic_toolbar_refresh) 37 | var icHome: ImageView? = null 38 | 39 | private var unbinder: Unbinder? = null 40 | 41 | abstract val layoutId: Int 42 | 43 | protected abstract fun initializeDagger() 44 | 45 | protected abstract fun initializePresenter() 46 | 47 | override fun onCreate(savedInstanceState: Bundle?) { 48 | super.onCreate(savedInstanceState) 49 | setContentView(layoutId) 50 | unbinder = ButterKnife.bind(this) 51 | initializeDagger() 52 | initializePresenter() 53 | initializeToolbar() 54 | presenter.initialize(intent.extras) 55 | } 56 | 57 | override fun onStart() { 58 | super.onStart() 59 | presenter.start() 60 | } 61 | 62 | override fun onStop() { 63 | super.onStop() 64 | presenter.finalizeView() 65 | } 66 | 67 | private fun initializeToolbar() { 68 | if (toolbar != null) { 69 | setSupportActionBar(toolbar) 70 | supportActionBar?.title = "" 71 | } 72 | } 73 | 74 | override fun setUpIconVisibility(visible: Boolean) { 75 | val actionBar = supportActionBar 76 | actionBar?.setDisplayHomeAsUpEnabled(visible) 77 | } 78 | 79 | override fun setTitle(titleKey: String) { 80 | val actionBar = supportActionBar 81 | if (actionBar != null) { 82 | val title = findViewById(R.id.txt_toolbar_title) 83 | title?.text = titleKey 84 | } 85 | } 86 | 87 | override fun setSettingsIconVisibility(visibility: Boolean) { 88 | val actionBar = supportActionBar 89 | if (actionBar != null) { 90 | val icon = findViewById(R.id.ic_toolbar_setting) 91 | icon?.visibility = if (visibility) VISIBLE else GONE 92 | } 93 | } 94 | 95 | override fun setRefreshVisibility(visibility: Boolean) { 96 | val actionBar = supportActionBar 97 | if (actionBar != null) { 98 | val icon = findViewById(R.id.ic_toolbar_refresh) 99 | icon?.visibility = if (visibility) VISIBLE else GONE 100 | } 101 | } 102 | 103 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 104 | when (item.itemId) { 105 | android.R.id.home -> finish() 106 | } 107 | return super.onOptionsItemSelected(item) 108 | } 109 | 110 | override fun onDestroy() { 111 | super.onDestroy() 112 | unbinder?.unbind() 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/BaseFragment.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base 2 | 3 | 4 | import android.os.Bundle 5 | import android.view.LayoutInflater 6 | import android.view.View 7 | import android.view.ViewGroup 8 | import android.widget.TextView 9 | import androidx.fragment.app.Fragment 10 | import com.task.R 11 | import com.task.ui.base.listeners.BaseView 12 | 13 | /** 14 | * Created by AhmedEltaher on 5/12/2016 15 | */ 16 | 17 | 18 | abstract class BaseFragment : Fragment(), BaseView { 19 | 20 | protected var presenter: Presenter<*>? = null 21 | 22 | abstract val layoutId: Int 23 | 24 | private val toolbarTitleKey: String? = null 25 | 26 | protected abstract fun initializeDagger() 27 | 28 | protected abstract fun initializePresenter() 29 | 30 | override fun onCreate(savedInstanceState: Bundle?) { 31 | super.onCreate(savedInstanceState) 32 | initializeDagger() 33 | initializePresenter() 34 | } 35 | 36 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 37 | savedInstanceState: Bundle?): View? { 38 | val view = inflater.inflate(layoutId, container, false) 39 | presenter?.initialize(arguments) 40 | return view 41 | } 42 | 43 | override fun onStart() { 44 | super.onStart() 45 | presenter?.start() 46 | } 47 | 48 | override fun onStop() { 49 | super.onStop() 50 | presenter?.finalizeView() 51 | } 52 | 53 | fun setTitle(title: String) { 54 | val actionBar = (activity as BaseActivity).supportActionBar 55 | if (actionBar != null) { 56 | val titleTextView = activity?.findViewById(R.id.txt_toolbar_title) 57 | if (!title.isEmpty()) { 58 | titleTextView?.text = title 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/Presenter.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base 2 | 3 | 4 | import android.os.Bundle 5 | 6 | import com.task.ui.base.listeners.BaseView 7 | 8 | import java.lang.ref.WeakReference 9 | import java.util.concurrent.atomic.AtomicBoolean 10 | 11 | /** 12 | * Created by AhmedEltaher on 5/12/2016 13 | */ 14 | 15 | 16 | abstract class Presenter { 17 | 18 | private var view: WeakReference? = null 19 | 20 | protected var isViewAlive = AtomicBoolean() 21 | 22 | fun getView(): T? { 23 | return view?.get() 24 | } 25 | 26 | fun setView(view: T) { 27 | this.view = WeakReference(view) 28 | } 29 | 30 | open fun initialize(extras: Bundle?) {} 31 | 32 | fun start() { 33 | isViewAlive.set(true) 34 | } 35 | 36 | fun finalizeView() { 37 | isViewAlive.set(false) 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/listeners/ActionBarView.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base.listeners 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016 5 | */ 6 | 7 | interface ActionBarView { 8 | 9 | fun setUpIconVisibility(visible: Boolean) 10 | 11 | fun setTitle(titleKey: String) 12 | 13 | fun setSettingsIconVisibility(visibility: Boolean) 14 | 15 | fun setRefreshVisibility(visibility: Boolean) 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/listeners/BaseCallback.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base.listeners 2 | 3 | import com.task.data.remote.dto.NewsModel 4 | 5 | /** 6 | * Created by ahmedeltaher on 3/22/17. 7 | */ 8 | 9 | interface BaseCallback { 10 | fun onSuccess(newsModel: NewsModel) 11 | 12 | fun onFail() 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/listeners/BaseView.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base.listeners 2 | 3 | /** 4 | * Created by ahmedeltaher on 3/20/17. 5 | */ 6 | 7 | interface BaseView 8 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/base/listeners/RecyclerItemListener.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.base.listeners 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016 5 | */ 6 | 7 | interface RecyclerItemListener { 8 | fun onItemSelected(position: Int) 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/details/DetailsActivity.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.details 2 | 3 | import com.squareup.picasso.Picasso 4 | import com.task.App 5 | import com.task.R 6 | import com.task.data.remote.dto.NewsItem 7 | import com.task.ui.base.BaseActivity 8 | import kotlinx.android.synthetic.main.details_layout.* 9 | import javax.inject.Inject 10 | 11 | /** 12 | * Created by AhmedEltaher on 11/12/16. 13 | */ 14 | 15 | class DetailsActivity : BaseActivity(), DetailsContract.View { 16 | 17 | @Inject 18 | lateinit var detailsPresenter: DetailsPresenter 19 | 20 | override val layoutId: Int 21 | get() = R.layout.details_layout 22 | 23 | override fun initializeDagger() { 24 | val app = applicationContext as App 25 | app.mainComponent?.inject(this@DetailsActivity) 26 | } 27 | 28 | override fun initializePresenter() { 29 | detailsPresenter.setView(this) 30 | super.presenter = detailsPresenter 31 | } 32 | 33 | override fun initializeView(newsItem: NewsItem) { 34 | tv_title?.text = newsItem.title ?: "" 35 | tv_description?.text = newsItem.abstract ?: "" 36 | if (!newsItem.multimedia.isNullOrEmpty()) { 37 | Picasso.get().load(newsItem.multimedia!!.last().url).placeholder(R.drawable.news) 38 | .into(iv_news_main_Image) 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/details/DetailsContract.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.details 2 | 3 | import com.task.data.remote.dto.NewsItem 4 | import com.task.ui.base.listeners.BaseView 5 | 6 | /** 7 | * Created by AhmedEltaher on 11/12/16. 8 | */ 9 | 10 | interface DetailsContract : BaseView { 11 | interface View : BaseView { 12 | fun initializeView(newsItem: NewsItem) 13 | } 14 | 15 | interface Presenter 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/details/DetailsPresenter.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.details 2 | 3 | import android.os.Bundle 4 | import com.task.data.remote.dto.NewsItem 5 | import com.task.ui.base.Presenter 6 | import com.task.utils.Constants 7 | import javax.inject.Inject 8 | 9 | /** 10 | * Created by AhmedEltaher on 11/12/16. 11 | */ 12 | 13 | class DetailsPresenter @Inject 14 | constructor() : Presenter(), DetailsContract.Presenter { 15 | 16 | private var newsItem: NewsItem? = null 17 | 18 | override fun initialize(extras: Bundle?) { 19 | super.initialize(extras) 20 | newsItem = extras?.getParcelable(Constants.NEWS_ITEM_KEY) 21 | getView()?.initializeView(newsItem!!) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/news/HomeActivity.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import android.view.View 4 | import android.view.View.GONE 5 | import android.view.View.VISIBLE 6 | import androidx.annotation.VisibleForTesting 7 | import androidx.recyclerview.widget.LinearLayoutManager 8 | import androidx.test.espresso.IdlingResource 9 | import butterknife.OnClick 10 | import com.task.App 11 | import com.task.R 12 | import com.task.data.remote.dto.NewsItem 13 | import com.task.ui.base.BaseActivity 14 | import com.task.ui.component.details.DetailsActivity 15 | import com.task.utils.Constants 16 | import com.task.utils.EspressoIdlingResource 17 | import kotlinx.android.synthetic.main.home_activity.* 18 | import org.jetbrains.anko.design.snackbar 19 | import org.jetbrains.anko.intentFor 20 | import javax.inject.Inject 21 | 22 | /** 23 | * Created by AhmedEltaher on 5/12/2016 24 | */ 25 | 26 | class HomeActivity : BaseActivity(), HomeContract.View { 27 | @Inject 28 | lateinit var homePresenter: HomePresenter 29 | 30 | override val layoutId: Int 31 | get() = R.layout.home_activity 32 | 33 | val countingIdlingResource: IdlingResource 34 | @VisibleForTesting 35 | get() = EspressoIdlingResource.idlingResource 36 | 37 | override fun initializeDagger() { 38 | val app = applicationContext as App 39 | app.mainComponent?.inject(this@HomeActivity) 40 | } 41 | 42 | override fun initializePresenter() { 43 | homePresenter.setView(this) 44 | super.presenter = homePresenter 45 | 46 | } 47 | 48 | override fun initializeNewsList(news: List) { 49 | val newsAdapter = NewsAdapter(homePresenter.getRecyclerItemListener(), news) 50 | val layoutManager = LinearLayoutManager(this) 51 | rv_news_list.layoutManager = layoutManager 52 | rv_news_list.setHasFixedSize(true) 53 | rv_news_list.adapter = newsAdapter 54 | } 55 | 56 | override fun setLoaderVisibility(isVisible: Boolean) { 57 | pb_loading.visibility = if (isVisible) VISIBLE else GONE 58 | } 59 | 60 | override fun navigateToDetailsScreen(news: NewsItem) { 61 | startActivity(intentFor(Constants.NEWS_ITEM_KEY to news)) 62 | } 63 | 64 | override fun setNoDataVisibility(isVisible: Boolean) { 65 | tv_no_data.visibility = if (isVisible) VISIBLE else GONE 66 | } 67 | 68 | override fun setListVisibility(isVisible: Boolean) { 69 | rl_news_list.visibility = if (isVisible) VISIBLE else GONE 70 | } 71 | 72 | override fun showSearchError() { 73 | rl_news_list.snackbar(R.string.search_error) 74 | } 75 | 76 | override fun showNoNewsError() { 77 | rl_news_list.snackbar(R.string.news_error) 78 | } 79 | 80 | override fun incrementCountingIdlingResource() { 81 | EspressoIdlingResource.increment() 82 | } 83 | 84 | override fun decrementCountingIdlingResource() { 85 | EspressoIdlingResource.decrement() 86 | } 87 | 88 | @OnClick(R.id.ic_toolbar_setting, R.id.ic_toolbar_refresh, R.id.btn_search) 89 | fun onClick(view: View) { 90 | when (view.id) { 91 | R.id.ic_toolbar_refresh -> homePresenter.getNews() 92 | R.id.btn_search -> homePresenter.onSearchClick(et_search.text.toString()) 93 | } 94 | } 95 | 96 | override fun onDestroy() { 97 | super.onDestroy() 98 | homePresenter.unSubscribe() 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/news/HomeContract.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import com.task.data.remote.dto.NewsItem 4 | import com.task.ui.base.listeners.BaseView 5 | import com.task.ui.base.listeners.RecyclerItemListener 6 | 7 | /** 8 | * Created by AhmedEltaher on 5/12/2016 9 | */ 10 | 11 | interface HomeContract { 12 | 13 | interface View : BaseView { 14 | fun initializeNewsList(news: List) 15 | 16 | fun setLoaderVisibility(isVisible: Boolean) 17 | 18 | fun navigateToDetailsScreen(news: NewsItem) 19 | 20 | fun setNoDataVisibility(isVisible: Boolean) 21 | 22 | fun setListVisibility(isVisible: Boolean) 23 | 24 | fun showSearchError() 25 | 26 | fun showNoNewsError() 27 | 28 | fun incrementCountingIdlingResource() 29 | 30 | fun decrementCountingIdlingResource() 31 | } 32 | 33 | 34 | interface Presenter { 35 | 36 | fun getRecyclerItemListener():RecyclerItemListener 37 | 38 | fun getNews() 39 | 40 | fun onSearchClick(newsTitle: String) 41 | 42 | fun unSubscribe() 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/news/HomePresenter.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import android.os.Bundle 4 | import com.task.data.remote.dto.NewsItem 5 | import com.task.data.remote.dto.NewsModel 6 | import com.task.ui.base.Presenter 7 | import com.task.ui.base.listeners.BaseCallback 8 | import com.task.ui.base.listeners.RecyclerItemListener 9 | import com.task.usecase.NewsUseCase 10 | import com.task.utils.ObjectUtil 11 | import javax.inject.Inject 12 | 13 | /** 14 | * Created by AhmedEltaher on 5/12/2016 15 | */ 16 | 17 | class HomePresenter @Inject 18 | constructor(private val newsUseCase: NewsUseCase) : Presenter(), HomeContract 19 | .Presenter, RecyclerItemListener { 20 | var newsModel: NewsModel? = null 21 | 22 | override fun getRecyclerItemListener(): RecyclerItemListener { 23 | return this 24 | } 25 | 26 | override fun onItemSelected(position: Int) { 27 | getView()?.navigateToDetailsScreen(newsModel?.newsItems!![position]) 28 | } 29 | 30 | private val callback = object : BaseCallback { 31 | override fun onSuccess(newsModel: NewsModel) { 32 | getView()?.decrementCountingIdlingResource() 33 | this@HomePresenter.newsModel = newsModel 34 | var newsItems: List? = null 35 | if (!ObjectUtil.isNull(newsModel)) { 36 | newsItems = newsModel.newsItems 37 | } 38 | if (!ObjectUtil.isNull(newsItems) && !newsItems!!.isEmpty()) { 39 | getView()?.initializeNewsList(newsModel.newsItems!!) 40 | showList(true) 41 | } else { 42 | showList(false) 43 | } 44 | getView()?.setLoaderVisibility(false) 45 | } 46 | 47 | override fun onFail() { 48 | getView()?.decrementCountingIdlingResource() 49 | showList(false) 50 | getView()?.setLoaderVisibility(false) 51 | } 52 | } 53 | 54 | override fun initialize(extras: Bundle?) { 55 | super.initialize(extras) 56 | getNews() 57 | } 58 | 59 | override fun getNews() { 60 | getView()?.setLoaderVisibility(true) 61 | getView()?.setNoDataVisibility(false) 62 | getView()?.setListVisibility(false) 63 | getView()?.incrementCountingIdlingResource() 64 | newsUseCase.getNews(callback) 65 | } 66 | 67 | override fun unSubscribe() { 68 | } 69 | 70 | override fun onSearchClick(newsTitle: String) { 71 | val news = newsModel!!.newsItems 72 | if (!newsTitle.isEmpty() && !news.isNullOrEmpty()) { 73 | val newsItem = newsUseCase.searchByTitle(news, newsTitle) 74 | if (newsItem != null) { 75 | getView()?.navigateToDetailsScreen(newsItem) 76 | } else { 77 | getView()?.showSearchError() 78 | } 79 | } else { 80 | getView()?.showSearchError() 81 | } 82 | } 83 | 84 | private fun showList(isVisible: Boolean) { 85 | getView()?.setNoDataVisibility(!isVisible) 86 | getView()?.setListVisibility(isVisible) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/news/NewsAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import android.view.LayoutInflater 4 | import android.view.ViewGroup 5 | import androidx.recyclerview.widget.RecyclerView 6 | import com.task.R 7 | import com.task.data.remote.dto.NewsItem 8 | import com.task.ui.base.listeners.RecyclerItemListener 9 | 10 | /** 11 | * Created by AhmedEltaher on 5/12/2016. 12 | */ 13 | 14 | class NewsAdapter(private val onItemClickListener: RecyclerItemListener, private val news: List) : RecyclerView.Adapter() { 15 | 16 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder { 17 | val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false) 18 | return NewsViewHolder(view) 19 | } 20 | 21 | override fun onBindViewHolder(holder: NewsViewHolder, position: Int) { 22 | holder.bind(position, news[position], onItemClickListener) 23 | } 24 | 25 | override fun getItemCount(): Int { 26 | return news.size 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/news/NewsViewHolder.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import android.view.View 4 | import androidx.recyclerview.widget.RecyclerView 5 | import com.squareup.picasso.Picasso 6 | import com.task.App 7 | import com.task.R 8 | import com.task.data.remote.dto.NewsItem 9 | import com.task.ui.base.listeners.RecyclerItemListener 10 | import kotlinx.android.extensions.LayoutContainer 11 | import kotlinx.android.synthetic.main.news_item.* 12 | 13 | /** 14 | * Created by AhmedEltaher on 5/12/2016. 15 | */ 16 | 17 | class NewsViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { 18 | 19 | fun bind(position: Int, newsItem: NewsItem, recyclerItemListener: RecyclerItemListener) { 20 | tv_caption.text = newsItem.abstract ?: "" 21 | tv_title.text = newsItem.title ?: "" 22 | 23 | if (!newsItem.multimedia.isNullOrEmpty() && newsItem.multimedia!!.size > 3) { 24 | val url: String? = newsItem.multimedia!![3].url 25 | Picasso.get().load(url).placeholder(App.getDrawableById(R.drawable.news)).into(iv_news_item_image) 26 | } 27 | rl_news_item.setOnClickListener { recyclerItemListener.onItemSelected(position) } 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/splash/SplashActivity.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.splash 2 | 3 | import android.os.Handler 4 | import com.task.App 5 | import com.task.R 6 | import com.task.ui.base.BaseActivity 7 | import com.task.ui.component.news.HomeActivity 8 | import com.task.utils.Constants 9 | import org.jetbrains.anko.startActivity 10 | import javax.inject.Inject 11 | 12 | /** 13 | * Created by AhmedEltaher on 5/12/2016 14 | */ 15 | 16 | class SplashActivity : BaseActivity(), SplashContract.View { 17 | 18 | @Inject 19 | lateinit var splashPresenter: SplashPresenter 20 | 21 | override val layoutId: Int 22 | get() = R.layout.splash_layout 23 | 24 | override fun initializeDagger() { 25 | val app = applicationContext as App 26 | app.mainComponent?.inject(this@SplashActivity) 27 | } 28 | 29 | override fun initializePresenter() { 30 | splashPresenter.setView(this) 31 | super.presenter = splashPresenter 32 | } 33 | 34 | override fun NavigateToMainScreen() { 35 | Handler().postDelayed({ 36 | startActivity() 37 | finish() 38 | }, Constants.SPLASH_DELAY.toLong()) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/splash/SplashContract.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.splash 2 | 3 | import com.task.ui.base.listeners.BaseView 4 | 5 | /** 6 | * Created by AhmedEltaher on 5/12/2016 7 | */ 8 | 9 | interface SplashContract { 10 | interface View : BaseView { 11 | fun NavigateToMainScreen() 12 | } 13 | 14 | interface Presenter 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/ui/component/splash/SplashPresenter.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.splash 2 | 3 | import android.os.Bundle 4 | 5 | import com.task.ui.base.Presenter 6 | 7 | import javax.inject.Inject 8 | 9 | /** 10 | * Created by AhmedEltaher on 5/12/2016 11 | */ 12 | 13 | class SplashPresenter @Inject 14 | constructor() : Presenter(), SplashContract.Presenter { 15 | 16 | override fun initialize(extras: Bundle?) { 17 | super.initialize(extras) 18 | getView()?.NavigateToMainScreen() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/usecase/NewsUseCase.kt: -------------------------------------------------------------------------------- 1 | package com.task.usecase 2 | 3 | import com.task.data.DataRepository 4 | import com.task.data.remote.ServiceError 5 | import com.task.data.remote.dto.NewsItem 6 | import com.task.data.remote.dto.NewsModel 7 | import com.task.ui.base.listeners.BaseCallback 8 | import kotlinx.coroutines.CoroutineScope 9 | import kotlinx.coroutines.Dispatchers 10 | import kotlinx.coroutines.async 11 | import kotlinx.coroutines.launch 12 | import javax.inject.Inject 13 | import kotlin.coroutines.CoroutineContext 14 | 15 | 16 | /** 17 | * Created by AhmedEltaher on 5/12/2016 18 | */ 19 | 20 | class NewsUseCase @Inject 21 | constructor(private val dataRepository: DataRepository, override val coroutineContext: CoroutineContext) : UseCase,CoroutineScope { 22 | 23 | override fun getNews(callback: BaseCallback) { 24 | launch{ 25 | try { 26 | val serviceResponse = async(Dispatchers.IO) { dataRepository.requestNews() }.await() 27 | if (serviceResponse?.code == ServiceError.SUCCESS_CODE) { 28 | val newsModel = serviceResponse.data as NewsModel 29 | callback.onSuccess(newsModel) 30 | } else { 31 | callback.onFail() 32 | } 33 | } catch (e: Exception) { 34 | callback.onFail() 35 | } 36 | } 37 | } 38 | 39 | override fun searchByTitle(news: List, keyWord: String): NewsItem? { 40 | for (newsItem in news) { 41 | if (!newsItem.title.isNullOrEmpty() && newsItem.title!!.toLowerCase().contains(keyWord.toLowerCase())) { 42 | return newsItem 43 | } 44 | } 45 | return null 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/usecase/UseCase.kt: -------------------------------------------------------------------------------- 1 | package com.task.usecase 2 | 3 | import com.task.data.remote.dto.NewsItem 4 | import com.task.ui.base.listeners.BaseCallback 5 | 6 | /** 7 | * Created by ahmedeltaher on 3/22/17. 8 | */ 9 | 10 | interface UseCase { 11 | fun getNews(callback: BaseCallback) 12 | 13 | fun searchByTitle(news: List, keyWord: String): NewsItem? 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016 5 | */ 6 | 7 | class Constants { 8 | companion object INSTANCE { 9 | const val SPLASH_DELAY = 3000 10 | const val ERROR_UNDEFINED = -1 11 | const val BASE_URL = "https://api.nytimes.com/svc/" 12 | const val NEWS_ITEM_KEY = "NEWS_ITEM_KEY" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/EspressoIdlingResource.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | /* 4 | * Copyright 2015, The Android Open Source Project 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import androidx.test.espresso.IdlingResource 20 | 21 | 22 | /** 23 | * Contains a static reference to [IdlingResource], only available in the 'mock' build type. 24 | */ 25 | class EspressoIdlingResource { 26 | companion object INSTANCE { 27 | private const val RESOURCE = "GLOBAL" 28 | 29 | private val mCountingIdlingResource = SimpleCountingIdlingResource(RESOURCE) 30 | 31 | val idlingResource: IdlingResource 32 | get() = mCountingIdlingResource 33 | 34 | fun increment() { 35 | mCountingIdlingResource.increment() 36 | } 37 | 38 | fun decrement() { 39 | mCountingIdlingResource.decrement() 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/L.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | import com.task.BuildConfig 4 | import org.jetbrains.anko.* 5 | 6 | /** 7 | * Created by AhmedEltaher on 01/01/17. 8 | */ 9 | 10 | class L { 11 | companion object INSTANCE : AnkoLogger { 12 | 13 | fun d(tag: String, massage: String) { 14 | if (BuildConfig.DEBUG) { 15 | AnkoLogger(tag).debug { massage } 16 | } 17 | } 18 | 19 | fun i(tag: String, massage: String) { 20 | if (BuildConfig.DEBUG) { 21 | AnkoLogger(tag).info { massage } 22 | } 23 | } 24 | 25 | fun v(tag: String, massage: String) { 26 | if (BuildConfig.DEBUG) { 27 | AnkoLogger(tag).verbose { massage } 28 | } 29 | } 30 | 31 | fun e(tag: String, massage: String) { 32 | if (BuildConfig.DEBUG) { 33 | AnkoLogger(tag).error { massage } 34 | } 35 | } 36 | 37 | fun json(tag: String, massage: String) { 38 | if (BuildConfig.DEBUG) { 39 | AnkoLogger(tag).info { massage } 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/Network.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | import android.content.Context 4 | import android.net.ConnectivityManager 5 | import android.net.NetworkInfo 6 | 7 | /** 8 | * Created by AhmedEltaher on 06/11/16. 9 | */ 10 | 11 | class Network { 12 | 13 | companion object Utils { 14 | private fun getNetworkInfo(context: Context): NetworkInfo? { 15 | val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager 16 | return cm.activeNetworkInfo 17 | } 18 | 19 | fun isConnected(context: Context): Boolean { 20 | val info = getNetworkInfo(context) 21 | return info != null && info.isConnected 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/ObjectUtil.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | /** 4 | * Created by AhmedEltaher on 5/12/2016. 5 | */ 6 | 7 | class ObjectUtil { 8 | companion object INSTANCE { 9 | fun isNull(obj: Any?): Boolean { 10 | return obj == null 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/com/task/utils/SimpleCountingIdlingResource.kt: -------------------------------------------------------------------------------- 1 | package com.task.utils 2 | 3 | /* 4 | * Copyright (C) 2015 The Android Open Source Project 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | 20 | import androidx.test.espresso.IdlingResource 21 | import androidx.test.espresso.intent.Checks.checkNotNull 22 | import java.util.concurrent.atomic.AtomicInteger 23 | 24 | 25 | /** 26 | * A simple counter implementation of [IdlingResource] that determines idleness by 27 | * maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is 28 | * non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore] 29 | * behaves. 30 | * 31 | * 32 | * This class can then be used to wrap up operations that while in progress should block tests from 33 | * accessing the UI. 34 | */ 35 | class SimpleCountingIdlingResource 36 | /** 37 | * Creates a SimpleCountingIdlingResource 38 | * 39 | * @param resourceName the resource name this resource should report to Espresso. 40 | */ 41 | (resourceName: String) : IdlingResource { 42 | 43 | private val mResourceName: String = checkNotNull(resourceName) 44 | 45 | private val counter = AtomicInteger(0) 46 | 47 | // written from main thread, read from any thread. 48 | @Volatile 49 | private var resourceCallback: IdlingResource.ResourceCallback? = null 50 | 51 | override fun getName(): String { 52 | return mResourceName 53 | } 54 | 55 | override fun isIdleNow(): Boolean { 56 | return counter.get() == 0 57 | } 58 | 59 | override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) { 60 | this.resourceCallback = resourceCallback 61 | } 62 | 63 | /** 64 | * Increments the count of in-flight transactions to the resource being monitored. 65 | */ 66 | fun increment() { 67 | counter.getAndIncrement() 68 | } 69 | 70 | /** 71 | * Decrements the count of in-flight transactions to the resource being monitored. 72 | * 73 | * If this operation results in the counter falling below 0 - an exception is raised. 74 | * 75 | * @throws IllegalStateException if the counter is below 0. 76 | */ 77 | fun decrement() { 78 | val counterVal = counter.decrementAndGet() 79 | if (counterVal == 0) { 80 | // we've gone from non-zero to zero. That means we're idle now! Tell espresso. 81 | if (null != resourceCallback) { 82 | resourceCallback!!.onTransitionToIdle() 83 | } 84 | } 85 | 86 | if (counterVal < 0) { 87 | throw IllegalArgumentException("Counter has been corrupted!") 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/news.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/app/src/main/res/drawable-hdpi/news.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/news.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/app/src/main/res/drawable-mdpi/news.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/news.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/app/src/main/res/drawable-xhdpi/news.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/news.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/app/src/main/res/drawable-xxhdpi/news.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxxhdpi/news.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/app/src/main/res/drawable-xxxhdpi/news.png -------------------------------------------------------------------------------- /app/src/main/res/drawable/border.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 12 | 13 | 14 | 15 | 19 | 20 | 21 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/layout/details_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 14 | 15 | 25 | 26 | 35 | 36 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /app/src/main/res/layout/home_activity.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 13 | 17 | 22 | 34 | 35 | 48 | 49 | 56 | 57 | 58 | 59 | 66 | 67 | 68 | 76 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /app/src/main/res/layout/news_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 22 | 32 | 40 | 48 | 49 | 50 | 54 | -------------------------------------------------------------------------------- /app/src/main/res/layout/splash_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 24 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/res/layout/toolbar.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 18 | 19 | 25 | 26 | 32 | 33 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7dp 4 | 25sp 5 | 30sp 6 | 20dp 7 | 15dp 8 | 15dp 9 | 10dp 10 | 35dp 11 | 6dp 12 | 50dp 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Ahmed Task 3 | No Data 4 | Search by title 5 | there is no such title 6 | there is no news 7 | this is the news title some text to test the appearance of 8 | the view It\'s time for a truly uncompromising smartphone. One that was designed and 9 | manufactured by technical enthusiasts - in close coordination with the future users. A 10 | smartphone that perfectly combines fascinating technology, groundbreaking design and 11 | breakthrough innovation. It is time for the OnePlus 3. But do not rely on our word. Convince 12 | yourself. 13 | 14 | this is the news title 15 | News 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | 22 | 28 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/test/java/com/task/ui/component/news/HomePresenterTest.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import com.task.data.remote.dto.NewsModel 4 | import com.task.ui.base.listeners.BaseCallback 5 | import com.task.usecase.NewsUseCase 6 | import io.mockk.* 7 | import org.junit.jupiter.api.AfterEach 8 | import org.junit.jupiter.api.BeforeEach 9 | import org.junit.jupiter.api.Test 10 | import org.junit.jupiter.api.TestInstance 11 | 12 | 13 | @TestInstance(TestInstance.Lifecycle.PER_METHOD) 14 | class HomePresenterTest { 15 | private val newsUseCase: NewsUseCase = mockk() 16 | private val newsModelMock: NewsModel = mockk() 17 | private val homeContract: HomeContract.View = spyk() 18 | private val callback: BaseCallback = spyk() 19 | 20 | private var homePresenter: HomePresenter? = null 21 | private val newsTitle = "this is test" 22 | private val testModelsGenerator: TestModelsGenerator = TestModelsGenerator() 23 | 24 | @BeforeEach 25 | fun setUp() { 26 | clearMocks(newsModelMock) 27 | clearMocks(callback) 28 | homePresenter = HomePresenter(newsUseCase) 29 | homePresenter!!.setView(homeContract) 30 | } 31 | 32 | @Test 33 | fun getNewsList() { 34 | // Let's do a synchronous answer for the callback 35 | val newsModel = testModelsGenerator.generateNewsModel(newsTitle) 36 | //1- Mock 37 | val callbackCapture: CapturingSlot = slot() 38 | every { newsUseCase.getNews(callback = capture(callbackCapture!!)) } answers 39 | { callbackCapture.captured.onSuccess(newsModel!!) } 40 | //2-Call 41 | homePresenter!!.getNews() 42 | //3-verify 43 | assert(newsModel == homePresenter!!.newsModel!!) 44 | verify(exactly = 1, verifyBlock = { homeContract!!.setLoaderVisibility(true) }) 45 | verify(exactly = 2, verifyBlock = { homeContract!!.setNoDataVisibility(false) }) 46 | verify(exactly = 1, verifyBlock = { homeContract!!.setListVisibility(false) }) 47 | verify(exactly = 1, verifyBlock = { homeContract!!.setListVisibility(false) }) 48 | verify(exactly = 1, verifyBlock = { newsUseCase!!.getNews(callbackCapture!!.captured) }) 49 | } 50 | 51 | @Test 52 | fun testSearchSuccess() { 53 | val newsItem = testModelsGenerator.generateNewsItemModel(newsTitle) 54 | val newsModel = testModelsGenerator.generateNewsModel(newsTitle) 55 | //1- Mock 56 | val callbackCapture: CapturingSlot = slot() 57 | every { newsUseCase.getNews(callback = capture(callbackCapture!!)) } answers 58 | { callbackCapture.captured.onSuccess(newsModel!!) } 59 | every { newsUseCase.searchByTitle(newsModel!!.newsItems!!, newsTitle) } returns newsItem 60 | //2- Call 61 | homePresenter!!.getNews() 62 | homePresenter!!.onSearchClick(newsTitle) 63 | //3- Verify 64 | assert(newsModel == homePresenter!!.newsModel!!) 65 | verify(exactly = 1, verifyBlock = { homeContract!!.navigateToDetailsScreen(any()) }) 66 | } 67 | 68 | @Test 69 | fun testSearchFailedWhileEmptyList() { 70 | //1- Mock 71 | val newsModelWithEmptyList: NewsModel = testModelsGenerator.generateNewsModelWithEmptyList("stup") 72 | val callbackCapture: CapturingSlot = slot() 73 | every { newsUseCase.getNews(callback = capture(callbackCapture!!)) } answers 74 | { callbackCapture.captured.onSuccess(newsModelWithEmptyList) } 75 | every { newsUseCase.searchByTitle(newsModelWithEmptyList!!.newsItems!!, newsTitle) } returns null 76 | //2- Call 77 | homePresenter!!.getNews() 78 | homePresenter!!.onSearchClick(newsTitle) 79 | //3- Verify 80 | assert(0 == homePresenter?.newsModel?.newsItems?.size) 81 | verify(exactly = 1, verifyBlock = { homeContract!!.showSearchError() }) 82 | } 83 | 84 | @Test 85 | fun testSearchFailedWhenNothingMatches() { 86 | val newsModel = testModelsGenerator.generateNewsModel(newsTitle) 87 | //1- Mock 88 | val callbackCapture: CapturingSlot = slot() 89 | every { newsUseCase.getNews(callback = capture(callbackCapture!!)) } answers 90 | { callbackCapture.captured.onSuccess(newsModel!!) } 91 | every { newsUseCase.searchByTitle(newsModel!!.newsItems!!, newsTitle) } returns null 92 | //2- Call 93 | homePresenter!!.getNews() 94 | homePresenter!!.onSearchClick(newsTitle) 95 | //3- Verify 96 | assert(homePresenter?.newsModel?.newsItems?.isNullOrEmpty() == false) 97 | verify(exactly = 1, verifyBlock = { homeContract!!.showSearchError() }) 98 | } 99 | 100 | @AfterEach 101 | fun tearDown() { 102 | 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /app/src/test/java/com/task/ui/component/news/NewsUseCaseTest.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import com.task.data.DataRepository 4 | import com.task.data.remote.ServiceError 5 | import com.task.data.remote.ServiceResponse 6 | import com.task.data.remote.dto.NewsModel 7 | import com.task.ui.base.listeners.BaseCallback 8 | import com.task.usecase.NewsUseCase 9 | import io.mockk.coEvery 10 | import io.mockk.coVerify 11 | import io.mockk.junit5.MockKExtension 12 | import io.mockk.mockk 13 | import io.mockk.spyk 14 | import kotlinx.coroutines.Dispatchers 15 | import org.junit.jupiter.api.AfterEach 16 | import org.junit.jupiter.api.Assertions.assertEquals 17 | import org.junit.jupiter.api.Assertions.assertNotNull 18 | import org.junit.jupiter.api.BeforeEach 19 | import org.junit.jupiter.api.Test 20 | import org.junit.jupiter.api.extension.ExtendWith 21 | 22 | /** 23 | * Created by ahmedeltaher on 3/8/17. 24 | */ 25 | 26 | @ExtendWith(MockKExtension::class) 27 | class NewsUseCaseTest { 28 | 29 | private var dataRepository: DataRepository? = null 30 | private var callback: BaseCallback? = spyk() 31 | 32 | private lateinit var newsUseCase: NewsUseCase 33 | private val testModelsGenerator: TestModelsGenerator = TestModelsGenerator() 34 | private lateinit var newsModel: NewsModel 35 | 36 | @BeforeEach 37 | fun setUp() { 38 | dataRepository = DataRepository(mockk(), mockk()) 39 | newsUseCase = NewsUseCase(dataRepository!!,Dispatchers.IO) 40 | } 41 | 42 | @Test 43 | fun testGetNewsSuccessful() { 44 | newsModel = testModelsGenerator.generateNewsModel("Stup") 45 | val serviceResponse = ServiceResponse(code = ServiceError.SUCCESS_CODE, data = newsModel) 46 | coEvery { dataRepository!!.requestNews() } returns serviceResponse 47 | newsUseCase.getNews(callback!!) 48 | coVerify(exactly = 1, verifyBlock = { callback!!.onSuccess(any()) }) 49 | coVerify(exactly = 0, verifyBlock = { callback!!.onFail() }) 50 | } 51 | 52 | @Test 53 | fun testGetNewsFail() { 54 | val serviceResponse = ServiceResponse(code = ServiceError.ERROR_CODE, data = null) 55 | coEvery { dataRepository!!.requestNews() } returns serviceResponse 56 | newsUseCase.getNews(callback!!) 57 | coVerify(exactly = 0, verifyBlock = { callback!!.onSuccess(any()) }) 58 | coVerify(exactly = 1, verifyBlock = { callback!!.onFail() }) 59 | } 60 | 61 | @Test 62 | fun searchByTitleSuccess() { 63 | val stup = "this is news Title" 64 | val newsItem = newsUseCase.searchByTitle(testModelsGenerator.generateNewsModel(stup).newsItems!!, stup) 65 | assertNotNull(newsItem) 66 | assertEquals(newsItem!!.title, stup) 67 | } 68 | 69 | @Test 70 | fun searchByTitleFail() { 71 | val stupTitle = "this is news Title" 72 | val stupSearch = "search title" 73 | val newsItem = newsUseCase.searchByTitle(testModelsGenerator.generateNewsModel(stupTitle).newsItems!!, stupSearch) 74 | assertEquals(newsItem, null) 75 | } 76 | 77 | @AfterEach 78 | fun tearDown() { 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /app/src/test/java/com/task/ui/component/news/TestModelsGenerator.kt: -------------------------------------------------------------------------------- 1 | package com.task.ui.component.news 2 | 3 | import com.task.data.remote.ServiceError 4 | import com.task.data.remote.ServiceResponse 5 | import com.task.data.remote.dto.NewsItem 6 | import com.task.data.remote.dto.NewsModel 7 | import java.util.* 8 | 9 | /** 10 | * Created by ahmedEltaher on 3/8/17. 11 | */ 12 | 13 | class TestModelsGenerator { 14 | 15 | val newsSuccessfulModel: ServiceResponse 16 | get() { 17 | val stupString = "this is temp string" 18 | val newsModel = generateNewsModel(stupString) 19 | return ServiceResponse(ServiceError.SUCCESS_CODE, newsModel) 20 | } 21 | 22 | val newsErrorModel: ServiceResponse 23 | get() = ServiceResponse(ServiceError.ERROR_CODE, null) 24 | 25 | fun generateNewsModel(stup: String): NewsModel { 26 | val newsModel = NewsModel() 27 | newsModel.copyright = stup 28 | newsModel.lastUpdated = stup 29 | newsModel.section = stup 30 | newsModel.status = stup 31 | newsModel.numResults = 25L 32 | val newsItems = ArrayList() 33 | for (i in 0..24) { 34 | newsItems.add(generateNewsItemModel(stup)) 35 | } 36 | newsModel.newsItems = newsItems 37 | return newsModel 38 | } 39 | 40 | fun generateNewsModelWithEmptyList(stup: String): NewsModel { 41 | val newsModel = NewsModel() 42 | newsModel.copyright = stup 43 | newsModel.lastUpdated = stup 44 | newsModel.section = stup 45 | newsModel.status = stup 46 | newsModel.numResults = 25L 47 | val newsItems = ArrayList() 48 | newsModel.newsItems = newsItems 49 | return newsModel 50 | } 51 | 52 | fun generateNewsItemModel(stup: String): NewsItem { 53 | val newsItem = NewsItem() 54 | newsItem.title = stup 55 | newsItem.abstract = stup 56 | newsItem.url = stup 57 | return newsItem 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.50' 5 | ext.anko_version='0.10.8' 6 | repositories { 7 | google() 8 | jcenter() 9 | mavenCentral() 10 | maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' } 11 | maven { url "https://maven.google.com" } 12 | } 13 | dependencies { 14 | classpath 'com.android.tools.build:gradle:3.5.2' 15 | //ButterKnife 16 | classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0' 17 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50" 18 | // NOTE: Do not place your application dependencies here; they belong 19 | // in the individual module build.gradle files 20 | classpath 'com.google.gms:google-services:4.3.2' 21 | classpath 'com.android.support.test.espresso:espresso-idling-resource:3.0.2' 22 | 23 | } 24 | } 25 | 26 | allprojects { 27 | repositories { 28 | google() 29 | jcenter() 30 | mavenCentral() 31 | maven { url "https://jitpack.io" } 32 | maven { url "https://maven.google.com" } 33 | } 34 | } 35 | 36 | task clean(type: Delete) { 37 | delete rootProject.buildDir 38 | } 39 | -------------------------------------------------------------------------------- /googlec49bc29aa25b1e6d.html: -------------------------------------------------------------------------------- 1 | google-site-verification: googlec49bc29aa25b1e6d.html -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | android.enableJetifier=true 13 | android.useAndroidX=true 14 | org.gradle.jvmargs=-Xmx1536m 15 | 16 | # When configured, Gradle will run in incubating parallel mode. 17 | # This option should only be used with decoupled projects. More details, visit 18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 19 | # org.gradle.parallel=true 20 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Oct 29 16:57:11 CET 2019 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-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /readme-images/8399.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/readme-images/8399.png -------------------------------------------------------------------------------- /readme-images/android-mvp-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/readme-images/android-mvp-flow.png -------------------------------------------------------------------------------- /readme-images/androkotlin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedeltaher/Android-MVP-Architecture/e1254bdf94912defb673fed14862e24a19b36b74/readme-images/androkotlin.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------