├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── main.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── rkpandey │ │ └── blogexplorer │ │ ├── BlogPostAdapter.kt │ │ ├── MainActivity.kt │ │ ├── MainViewModel.kt │ │ ├── api │ │ ├── BlogApi.kt │ │ ├── HeaderInterceptor.kt │ │ └── RetrofitInstance.kt │ │ ├── detail │ │ ├── DetailActivity.kt │ │ └── DetailViewModel.kt │ │ ├── edit │ │ ├── EditActivity.kt │ │ ├── EditViewModel.kt │ │ └── ResultStatus.kt │ │ └── models │ │ ├── Company.kt │ │ ├── Post.kt │ │ └── User.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_detail.xml │ ├── activity_edit.xml │ ├── activity_main.xml │ └── item_blog_post.xml │ ├── menu │ └── menu_detail.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── values-night │ └── themes.xml │ └── values │ ├── colors.xml │ ├── strings.xml │ └── themes.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) deotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Copy To Branches 2 | on: 3 | workflow_dispatch: 4 | jobs: 5 | copy-to-branches: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | fetch-depth: 0 11 | - name: Copy To Branches Action 12 | uses: planetoftheweb/copy-to-branches@v1 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | .idea/ 6 | .idea/caches 7 | .idea/modules.xml 8 | .idea/navEditor.xml 9 | *.iml 10 | .idea/workspace.xml 11 | .idea/tasks.xml 12 | .idea/gradle.xml 13 | .idea/assetWizardSettings.xml 14 | .idea/dictionaries 15 | .idea/libraries 16 | .gradle/ 17 | **/build/ -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2021 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | ATTRIBUTIONS: 8 | 9 | Retrofit 10 | https://github.com/square/retrofit 11 | Copyright 2013 Square, Inc. 12 | License:Apache License 2.0 13 | http://www.apache.org/licenses/LICENSE-2.0 14 | 15 | Kotlin 16 | https://github.com/JetBrains/kotlin 17 | Copyright 2020 Jetbrains, Inc. 18 | License:Apache License 2.0 19 | http://www.apache.org/licenses/LICENSE-2.0 20 | 21 | Please note, this project may automatically load third party code from external 22 | repositories (for example, NPM modules, Composer packages, or other dependencies). 23 | If so, such third party code may be subject to other license terms than as set 24 | forth above. In addition, such third party code may also depend on and load 25 | multiple tiers of dependencies. Please review the applicable licenses of the 26 | additional dependencies. 27 | 28 | 29 | =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 30 | 31 | Apache License 32 | Version 2.0, January 2004 33 | http://www.apache.org/licenses/ 34 | 35 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 36 | 37 | 1. Definitions. 38 | 39 | "License" shall mean the terms and conditions for use, reproduction, 40 | and distribution as defined by Sections 1 through 9 of this document. 41 | 42 | "Licensor" shall mean the copyright owner or entity authorized by 43 | the copyright owner that is granting the License. 44 | 45 | "Legal Entity" shall mean the union of the acting entity and all 46 | other entities that control, are controlled by, or are under common 47 | control with that entity. For the purposes of this definition, 48 | "control" means (i) the power, direct or indirect, to cause the 49 | direction or management of such entity, whether by contract or 50 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 51 | outstanding shares, or (iii) beneficial ownership of such entity. 52 | 53 | "You" (or "Your") shall mean an individual or Legal Entity 54 | exercising permissions granted by this License. 55 | 56 | "Source" form shall mean the preferred form for making modifications, 57 | including but not limited to software source code, documentation 58 | source, and configuration files. 59 | 60 | "Object" form shall mean any form resulting from mechanical 61 | transformation or translation of a Source form, including but 62 | not limited to compiled object code, generated documentation, 63 | and conversions to other media types. 64 | 65 | "Work" shall mean the work of authorship, whether in Source or 66 | Object form, made available under the License, as indicated by a 67 | copyright notice that is included in or attached to the work 68 | (an example is provided in the Appendix below). 69 | 70 | "Derivative Works" shall mean any work, whether in Source or Object 71 | form, that is based on (or derived from) the Work and for which the 72 | editorial revisions, annotations, elaborations, or other modifications 73 | represent, as a whole, an original work of authorship. For the purposes 74 | of this License, Derivative Works shall not include works that remain 75 | separable from, or merely link (or bind by name) to the interfaces of, 76 | the Work and Derivative Works thereof. 77 | 78 | "Contribution" shall mean any work of authorship, including 79 | the original version of the Work and any modifications or additions 80 | to that Work or Derivative Works thereof, that is intentionally 81 | submitted to Licensor for inclusion in the Work by the copyright owner 82 | or by an individual or Legal Entity authorized to submit on behalf of 83 | the copyright owner. For the purposes of this definition, "submitted" 84 | means any form of electronic, verbal, or written communication sent 85 | to the Licensor or its representatives, including but not limited to 86 | communication on electronic mailing lists, source code control systems, 87 | and issue tracking systems that are managed by, or on behalf of, the 88 | Licensor for the purpose of discussing and improving the Work, but 89 | excluding communication that is conspicuously marked or otherwise 90 | designated in writing by the copyright owner as "Not a Contribution." 91 | 92 | "Contributor" shall mean Licensor and any individual or Legal Entity 93 | on behalf of whom a Contribution has been received by Licensor and 94 | subsequently incorporated within the Work. 95 | 96 | 2. Grant of Copyright License. Subject to the terms and conditions of 97 | this License, each Contributor hereby grants to You a perpetual, 98 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 99 | copyright license to reproduce, prepare Derivative Works of, 100 | publicly display, publicly perform, sublicense, and distribute the 101 | Work and such Derivative Works in Source or Object form. 102 | 103 | 3. Grant of Patent License. Subject to the terms and conditions of 104 | this License, each Contributor hereby grants to You a perpetual, 105 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 106 | (except as stated in this section) patent license to make, have made, 107 | use, offer to sell, sell, import, and otherwise transfer the Work, 108 | where such license applies only to those patent claims licensable 109 | by such Contributor that are necessarily infringed by their 110 | Contribution(s) alone or by combination of their Contribution(s) 111 | with the Work to which such Contribution(s) was submitted. If You 112 | institute patent litigation against any entity (including a 113 | cross-claim or counterclaim in a lawsuit) alleging that the Work 114 | or a Contribution incorporated within the Work constitutes direct 115 | or contributory patent infringement, then any patent licenses 116 | granted to You under this License for that Work shall terminate 117 | as of the date such litigation is filed. 118 | 119 | 4. Redistribution. You may reproduce and distribute copies of the 120 | Work or Derivative Works thereof in any medium, with or without 121 | modifications, and in Source or Object form, provided that You 122 | meet the following conditions: 123 | 124 | (a) You must give any other recipients of the Work or 125 | Derivative Works a copy of this License; and 126 | 127 | (b) You must cause any modified files to carry prominent notices 128 | stating that You changed the files; and 129 | 130 | (c) You must retain, in the Source form of any Derivative Works 131 | that You distribute, all copyright, patent, trademark, and 132 | attribution notices from the Source form of the Work, 133 | excluding those notices that do not pertain to any part of 134 | the Derivative Works; and 135 | 136 | (d) If the Work includes a "NOTICE" text file as part of its 137 | distribution, then any Derivative Works that You distribute must 138 | include a readable copy of the attribution notices contained 139 | within such NOTICE file, excluding those notices that do not 140 | pertain to any part of the Derivative Works, in at least one 141 | of the following places: within a NOTICE text file distributed 142 | as part of the Derivative Works; within the Source form or 143 | documentation, if provided along with the Derivative Works; or, 144 | within a display generated by the Derivative Works, if and 145 | wherever such third-party notices normally appear. The contents 146 | of the NOTICE file are for informational purposes only and 147 | do not modify the License. You may add Your own attribution 148 | notices within Derivative Works that You distribute, alongside 149 | or as an addendum to the NOTICE text from the Work, provided 150 | that such additional attribution notices cannot be construed 151 | as modifying the License. 152 | 153 | You may add Your own copyright statement to Your modifications and 154 | may provide additional or different license terms and conditions 155 | for use, reproduction, or distribution of Your modifications, or 156 | for any such Derivative Works as a whole, provided Your use, 157 | reproduction, and distribution of the Work otherwise complies with 158 | the conditions stated in this License. 159 | 160 | 5. Submission of Contributions. Unless You explicitly state otherwise, 161 | any Contribution intentionally submitted for inclusion in the Work 162 | by You to the Licensor shall be under the terms and conditions of 163 | this License, without any additional terms or conditions. 164 | Notwithstanding the above, nothing herein shall supersede or modify 165 | the terms of any separate license agreement you may have executed 166 | with Licensor regarding such Contributions. 167 | 168 | 6. Trademarks. This License does not grant permission to use the trade 169 | names, trademarks, service marks, or product names of the Licensor, 170 | except as required for reasonable and customary use in describing the 171 | origin of the Work and reproducing the content of the NOTICE file. 172 | 173 | 7. Disclaimer of Warranty. Unless required by applicable law or 174 | agreed to in writing, Licensor provides the Work (and each 175 | Contributor provides its Contributions) on an "AS IS" BASIS, 176 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 177 | implied, including, without limitation, any warranties or conditions 178 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 179 | PARTICULAR PURPOSE. You are solely responsible for determining the 180 | appropriateness of using or redistributing the Work and assume any 181 | risks associated with Your exercise of permissions under this License. 182 | 183 | 8. Limitation of Liability. In no event and under no legal theory, 184 | whether in tort (including negligence), contract, or otherwise, 185 | unless required by applicable law (such as deliberate and grossly 186 | negligent acts) or agreed to in writing, shall any Contributor be 187 | liable to You for damages, including any direct, indirect, special, 188 | incidental, or consequential damages of any character arising as a 189 | result of this License or out of the use or inability to use the 190 | Work (including but not limited to damages for loss of goodwill, 191 | work stoppage, computer failure or malfunction, or any and all 192 | other commercial damages or losses), even if such Contributor 193 | has been advised of the possibility of such damages. 194 | 195 | 9. Accepting Warranty or Additional Liability. While redistributing 196 | the Work or Derivative Works thereof, You may choose to offer, 197 | and charge a fee for, acceptance of support, warranty, indemnity, 198 | or other liability obligations and/or rights consistent with this 199 | License. However, in accepting such obligations, You may act only 200 | on Your own behalf and on Your sole responsibility, not on behalf 201 | of any other Contributor, and only if You agree to indemnify, 202 | defend, and hold each Contributor harmless for any liability 203 | incurred by, or claims asserted against, such Contributor by reason 204 | of your accepting any such warranty or additional liability. 205 | 206 | END OF TERMS AND CONDITIONS 207 | 208 | APPENDIX: How to apply the Apache License to your work. 209 | 210 | To apply the Apache License to your work, attach the following 211 | boilerplate notice, with the fields enclosed by brackets "[]" 212 | replaced with your own identifying information. (Don't include 213 | the brackets!) The text should be enclosed in the appropriate 214 | comment syntax for the file format. We also recommend that a 215 | file or class name and description of purpose be included on the 216 | same "printed page" as the copyright notice for easier 217 | identification within third-party archives. 218 | 219 | Copyright [yyyy] [name of copyright owner] 220 | 221 | Licensed under the Apache License, Version 2.0 (the "License"); 222 | you may not use this file except in compliance with the License. 223 | You may obtain a copy of the License at 224 | 225 | http://www.apache.org/licenses/LICENSE-2.0 226 | 227 | Unless required by applicable law or agreed to in writing, software 228 | distributed under the License is distributed on an "AS IS" BASIS, 229 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 230 | See the License for the specific language governing permissions and 231 | limitations under the License. 232 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Development: Retrofit with Kotlin 2 | This is the repository for the LinkedIn Learning course Android Development: Retrofit with Kotlin. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![Android Development: Retrofit with Kotlin][lil-thumbnail-url] 5 | 6 | Many apps use your mobile phone’s internet connection to get data. On Android, the primary way that apps get and post data over the internet is with a library called Retrofit. This course shows you how to use Retrofit with idiomatic Kotlin code that you can apply directly to your Android app. Instructor Rahul Pandey covers everything you need to know to build rich, networked Android apps. Rahul starts with helping you understand APIs and their uses. He explains concurrency, coroutines in Kotlin, and how both can benefit your app. Rahul steps you through getting started with an Android Retrofit project, as well as retrieving and sending data and handling authentication in your Android app. Finally, Rahul covers several advanced configuration options related to Retrofit. 7 | 8 | ## Instructions 9 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access. 10 | 11 | ## Branches 12 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter. 13 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course. 14 | 15 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this: 16 | 17 | error: Your local changes to the following files would be overwritten by checkout: [files] 18 | Please commit your changes or stash them before you switch branches. 19 | Aborting 20 | 21 | To resolve this issue: 22 | 23 | Add changes to git using this command: git add . 24 | Commit changes using this command: git commit -m "some message" 25 | 26 | 27 | ### Instructor 28 | 29 | Rahul Pandey 30 | 31 | 32 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/rahul-pandey). 33 | 34 | [lil-course-url]: https://www.linkedin.com/learning/android-development-retrofit-with-kotlin 35 | [lil-thumbnail-url]: https://cdn.lynda.com/course/2882228/2882228-1628621457878-16x9.jpg 36 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | compileSdkVersion 30 8 | buildToolsVersion "30.0.2" 9 | 10 | defaultConfig { 11 | applicationId "com.rkpandey.blogexplorer" 12 | minSdkVersion 21 13 | targetSdkVersion 30 14 | versionCode 1 15 | versionName "1.0" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | release { 22 | minifyEnabled true 23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | buildFeatures { 27 | viewBinding true 28 | } 29 | compileOptions { 30 | sourceCompatibility JavaVersion.VERSION_1_8 31 | targetCompatibility JavaVersion.VERSION_1_8 32 | } 33 | kotlinOptions { 34 | jvmTarget = '1.8' 35 | } 36 | } 37 | 38 | dependencies { 39 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 40 | implementation 'androidx.core:core-ktx:1.3.2' 41 | implementation 'androidx.appcompat:appcompat:1.2.0' 42 | implementation 'com.google.android.material:material:1.3.0' 43 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 44 | implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1' 45 | implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1' 46 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 47 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 48 | 49 | implementation 'com.squareup.retrofit2:retrofit:2.9.0' 50 | implementation 'com.squareup.retrofit2:converter-moshi:2.9.0' 51 | 52 | implementation 'com.squareup.moshi:moshi-kotlin:1.12.0' 53 | implementation 'com.squareup.moshi:moshi-adapters:1.12.0' 54 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | # Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java. 24 | -dontwarn org.codehaus.mojo.animal_sniffer.* -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/BlogPostAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer 2 | 3 | import android.content.Context 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import android.widget.TextView 8 | import androidx.recyclerview.widget.RecyclerView 9 | import com.rkpandey.blogexplorer.models.Post 10 | 11 | class BlogPostAdapter( 12 | private val context: Context, 13 | private val posts: List, 14 | private val itemClickListener: ItemClickListener 15 | ) : RecyclerView.Adapter() { 16 | 17 | interface ItemClickListener { 18 | fun onItemClick(post: Post) 19 | } 20 | 21 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { 22 | val view = LayoutInflater.from(context).inflate(R.layout.item_blog_post, parent, false) 23 | return ViewHolder(view) 24 | } 25 | 26 | override fun getItemCount() = posts.size 27 | 28 | override fun onBindViewHolder(holder: ViewHolder, position: Int) { 29 | holder.bind(posts[position]) 30 | } 31 | 32 | inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { 33 | private val tvId = itemView.findViewById(R.id.tvId) 34 | private val tvTitle = itemView.findViewById(R.id.tvTitle) 35 | private val tvBody = itemView.findViewById(R.id.tvBlogBody) 36 | 37 | fun bind(post: Post) { 38 | tvId.text = "Post #${post.id}" 39 | tvTitle.text = post.title 40 | tvBody.text = post.content 41 | itemView.setOnClickListener { 42 | itemClickListener.onItemClick(post) 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.util.Log 6 | import android.view.View 7 | import android.widget.Toast 8 | import androidx.appcompat.app.AppCompatActivity 9 | import androidx.lifecycle.Observer 10 | import androidx.lifecycle.ViewModelProvider 11 | import androidx.recyclerview.widget.LinearLayoutManager 12 | import com.rkpandey.blogexplorer.databinding.ActivityMainBinding 13 | import com.rkpandey.blogexplorer.detail.DetailActivity 14 | import com.rkpandey.blogexplorer.models.Post 15 | 16 | private const val TAG = "MainActivity" 17 | const val EXTRA_POST_ID = "EXTRA_POST_ID" 18 | class MainActivity : AppCompatActivity() { 19 | private lateinit var viewModel: MainViewModel 20 | private lateinit var binding: ActivityMainBinding 21 | private lateinit var blogPostAdapter: BlogPostAdapter 22 | private val blogPosts = mutableListOf() 23 | 24 | override fun onCreate(savedInstanceState: Bundle?) { 25 | super.onCreate(savedInstanceState) 26 | binding = ActivityMainBinding.inflate(layoutInflater) 27 | setContentView(binding.root) 28 | viewModel = ViewModelProvider(this).get(MainViewModel::class.java) 29 | 30 | viewModel.posts.observe(this, Observer { posts -> 31 | Log.i(TAG, "Number of posts: ${posts.size}") 32 | val numElements = blogPosts.size 33 | blogPosts.clear() 34 | blogPosts.addAll(posts) 35 | blogPostAdapter.notifyDataSetChanged() 36 | binding.rvPosts.smoothScrollToPosition(numElements) 37 | }) 38 | viewModel.isLoading.observe(this, Observer { isLoading -> 39 | Log.i(TAG, "isLoading $isLoading") 40 | binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE 41 | }) 42 | viewModel.errorMessage.observe(this, Observer { errorMessage -> 43 | if (errorMessage == null) { 44 | binding.tvError.visibility = View.GONE 45 | } else { 46 | binding.tvError.visibility = View.VISIBLE 47 | Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show() 48 | } 49 | }) 50 | 51 | blogPostAdapter = BlogPostAdapter(this, blogPosts, object : BlogPostAdapter.ItemClickListener { 52 | override fun onItemClick(post: Post) { 53 | // navigate to new activity 54 | val intent = Intent(this@MainActivity, DetailActivity::class.java) 55 | intent.putExtra(EXTRA_POST_ID, post.id) 56 | startActivity(intent) 57 | } 58 | }) 59 | binding.rvPosts.adapter = blogPostAdapter 60 | binding.rvPosts.layoutManager = LinearLayoutManager(this) 61 | 62 | binding.button.setOnClickListener { 63 | viewModel.getPosts() 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/MainViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer 2 | 3 | import android.util.Log 4 | import androidx.lifecycle.LiveData 5 | import androidx.lifecycle.MutableLiveData 6 | import androidx.lifecycle.ViewModel 7 | import androidx.lifecycle.viewModelScope 8 | import com.rkpandey.blogexplorer.api.RetrofitInstance 9 | import com.rkpandey.blogexplorer.models.Post 10 | import kotlinx.coroutines.launch 11 | import java.lang.Exception 12 | 13 | private const val TAG = "MainViewModel" 14 | class MainViewModel : ViewModel() { 15 | private val _posts: MutableLiveData> = MutableLiveData() 16 | val posts: LiveData> 17 | get() = _posts 18 | 19 | private val _isLoading = MutableLiveData(false) 20 | val isLoading: LiveData 21 | get() = _isLoading 22 | 23 | private val _errorMessage = MutableLiveData(null) 24 | val errorMessage: LiveData 25 | get() = _errorMessage 26 | 27 | private var currentPage = 1 28 | 29 | fun getPosts() { 30 | viewModelScope.launch { 31 | Log.i(TAG, "Query with page $currentPage") 32 | _errorMessage.value = null 33 | _isLoading.value = true 34 | try { 35 | val fetchedPosts = RetrofitInstance.api.getPosts(currentPage) 36 | currentPage += 1 37 | Log.i(TAG, "Got posts: $fetchedPosts") 38 | val currentPosts = _posts.value ?: emptyList() 39 | _posts.value = currentPosts + fetchedPosts 40 | } catch (e: Exception) { 41 | _errorMessage.value = e.message 42 | Log.e(TAG, "Exception $e") 43 | } finally { 44 | _isLoading.value = false 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/api/BlogApi.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.api 2 | 3 | import com.rkpandey.blogexplorer.models.Post 4 | import com.rkpandey.blogexplorer.models.User 5 | import retrofit2.Call 6 | import retrofit2.http.* 7 | 8 | interface BlogApi { 9 | @GET("posts") 10 | suspend fun getPosts(@Query("_page") page: Int = 1, @Query("_limit") limit: Int = 10): List 11 | 12 | @Headers("Platform: Android") 13 | @GET("posts/{id}") 14 | suspend fun getPost(@Path("id") postId: Int): Post 15 | 16 | @GET("users/{id}") 17 | suspend fun getUser(@Path("id") userId: Int): User 18 | 19 | // request body contains the complete new version 20 | @PUT("posts/{id}") 21 | suspend fun updatePost(@Path("id") postId: Int, @Body post: Post): Post 22 | 23 | // request body only needs to contain the specific changes to the resource 24 | @PATCH("posts/{id}") 25 | suspend fun patchPost(@Path("id") postId: Int, @Body params: Map): Post 26 | 27 | @DELETE("posts/{id}") 28 | suspend fun deletePost(@Header("Auth-Token") auth: String, @Path("id") postId: Int) 29 | 30 | @POST("posts/") 31 | suspend fun createPost(@Body post: Post): Post 32 | 33 | @FormUrlEncoded 34 | @POST("posts/") 35 | suspend fun createPostUrlEncode( 36 | @Field("userId") userId: Int, 37 | @Field("title") title: String, 38 | @Field("body") content: String 39 | ): Post 40 | 41 | @GET("posts/{id}") 42 | fun getPostViaCallback(@Path("id") postId: Int): Call 43 | 44 | @GET("users/{id}") 45 | fun getUserViaCallback(@Path("id") userId: Int): Call 46 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/api/HeaderInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.api 2 | 3 | import okhttp3.Interceptor 4 | import okhttp3.Response 5 | 6 | class HeaderInterceptor : Interceptor { 7 | override fun intercept(chain: Interceptor.Chain): Response { 8 | val request = chain.request() 9 | .newBuilder() 10 | .addHeader("User-Agent", "Blog-Explorer-Sample") 11 | .build() 12 | return chain.proceed(request) 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/api/RetrofitInstance.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.api 2 | 3 | import com.squareup.moshi.Moshi 4 | import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter 5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory 6 | import okhttp3.OkHttpClient 7 | import retrofit2.Retrofit 8 | import retrofit2.converter.moshi.MoshiConverterFactory 9 | import java.util.* 10 | 11 | private const val BASE_URL = "https://jsonplaceholder.typicode.com/" 12 | object RetrofitInstance { 13 | 14 | private val client = OkHttpClient.Builder() 15 | .addInterceptor(HeaderInterceptor()) 16 | .build() 17 | 18 | private val moshi = Moshi.Builder() 19 | .add(Date::class.java, Rfc3339DateJsonAdapter()) 20 | .addLast(KotlinJsonAdapterFactory()) 21 | .build() 22 | 23 | /** 24 | * Use the Retrofit builder to build a retrofit object using a Moshi converter. 25 | */ 26 | private val retrofit by lazy { 27 | Retrofit.Builder() 28 | .baseUrl(BASE_URL) 29 | .client(client) 30 | .addConverterFactory(MoshiConverterFactory.create(moshi)) 31 | .build() 32 | } 33 | 34 | val api: BlogApi by lazy { 35 | retrofit.create(BlogApi::class.java) 36 | } 37 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/detail/DetailActivity.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.detail 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.util.Log 6 | import android.view.Menu 7 | import android.view.MenuItem 8 | import android.view.View 9 | import androidx.appcompat.app.AppCompatActivity 10 | import androidx.lifecycle.Observer 11 | import androidx.lifecycle.ViewModelProvider 12 | import com.rkpandey.blogexplorer.EXTRA_POST_ID 13 | import com.rkpandey.blogexplorer.R 14 | import com.rkpandey.blogexplorer.databinding.ActivityDetailBinding 15 | import com.rkpandey.blogexplorer.edit.EditActivity 16 | 17 | const val EXTRA_POST = "EXTRA_POST" 18 | private const val TAG = "DetailActivity" 19 | class DetailActivity : AppCompatActivity() { 20 | 21 | private lateinit var viewModel: DetailViewModel 22 | private lateinit var binding: ActivityDetailBinding 23 | 24 | override fun onCreate(savedInstanceState: Bundle?) { 25 | super.onCreate(savedInstanceState) 26 | binding = ActivityDetailBinding.inflate(layoutInflater) 27 | setContentView(binding.root) 28 | val postId = intent.getIntExtra(EXTRA_POST_ID, -1) 29 | 30 | viewModel = ViewModelProvider(this).get(DetailViewModel::class.java) 31 | viewModel.isLoading.observe(this, Observer { isLoading -> 32 | binding.detailProgressBar.visibility = if (isLoading) View.VISIBLE else View.GONE 33 | binding.clContent.visibility = if (isLoading) View.GONE else View.VISIBLE 34 | }) 35 | viewModel.post.observe(this, Observer { post -> 36 | binding.tvPostId.text = "Post #${post.id}" 37 | binding.tvTitle.text = post.title 38 | binding.tvBody.text = post.content 39 | }) 40 | 41 | viewModel.user.observe(this, Observer { user -> 42 | binding.tvUserName.text = user.name 43 | binding.tvUserEmail.text = user.email 44 | binding.tvUsername.text = user.username 45 | binding.tvWebsite.text = user.website 46 | }) 47 | 48 | viewModel.getPostDetails(postId) 49 | } 50 | 51 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 52 | menuInflater.inflate(R.menu.menu_detail, menu) 53 | return true 54 | } 55 | 56 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 57 | if (item.itemId == R.id.miEdit) { 58 | Log.i(TAG, "Navigate to edit screen") 59 | viewModel.post.observe(this, Observer { post -> 60 | val intent = Intent(this, EditActivity::class.java) 61 | intent.putExtra(EXTRA_POST, post) 62 | startActivity(intent) 63 | }) 64 | } 65 | return super.onOptionsItemSelected(item) 66 | } 67 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/detail/DetailViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.detail 2 | 3 | import android.util.Log 4 | import androidx.lifecycle.LiveData 5 | import androidx.lifecycle.MutableLiveData 6 | import androidx.lifecycle.ViewModel 7 | import androidx.lifecycle.viewModelScope 8 | import com.rkpandey.blogexplorer.api.RetrofitInstance 9 | import com.rkpandey.blogexplorer.models.Post 10 | import com.rkpandey.blogexplorer.models.User 11 | import kotlinx.coroutines.launch 12 | import retrofit2.Call 13 | import retrofit2.Callback 14 | import retrofit2.Response 15 | 16 | private const val TAG = "DetailViewModel" 17 | class DetailViewModel : ViewModel() { 18 | private val _isLoading = MutableLiveData(false) 19 | val isLoading: LiveData 20 | get() = _isLoading 21 | 22 | private val _post = MutableLiveData() 23 | val post: LiveData 24 | get() = _post 25 | 26 | private val _user = MutableLiveData() 27 | val user: LiveData 28 | get() = _user 29 | 30 | fun getPostDetails(postId: Int) { 31 | val api = RetrofitInstance.api 32 | // Coroutine style 33 | viewModelScope.launch { 34 | _isLoading.value = true 35 | val fetchedPost = api.getPost(postId) 36 | val fetchedUser = api.getUser(fetchedPost.userId) 37 | Log.i(TAG, "Fetched user $fetchedUser") 38 | _post.value = fetchedPost 39 | _user.value = fetchedUser 40 | _isLoading.value = false 41 | } 42 | 43 | // Callback style (alternative) 44 | // fetchDataCallbackStyle(postId) 45 | } 46 | 47 | private fun fetchDataCallbackStyle(postId: Int) { 48 | val api = RetrofitInstance.api 49 | _isLoading.value = true 50 | api.getPostViaCallback(postId).enqueue(object: Callback { 51 | override fun onFailure(call: Call, t: Throwable) { 52 | Log.e(TAG, "onFailure $t") 53 | } 54 | 55 | override fun onResponse(call: Call, response: Response) { 56 | if (response.isSuccessful) { 57 | val fetchedPost = response.body()!! 58 | Log.i(TAG, "onResponse post $fetchedPost") 59 | api.getUserViaCallback(fetchedPost.userId).enqueue(object: Callback { 60 | override fun onFailure(call: Call, t: Throwable) { 61 | Log.e(TAG, "onFailure $t") 62 | } 63 | 64 | override fun onResponse(call: Call, response: Response) { 65 | if (response.isSuccessful) { 66 | val fetchedUser = response.body()!! 67 | _post.value = fetchedPost 68 | _user.value = fetchedUser 69 | _isLoading.value = false 70 | Log.i(TAG, "onResponse user $fetchedUser") 71 | } 72 | Log.e(TAG, "response unsuccessful, code ${response.code()}") 73 | } 74 | }) 75 | } else { 76 | Log.e(TAG, "response unsuccessful, code ${response.code()}") 77 | } 78 | } 79 | }) 80 | } 81 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/edit/EditActivity.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.edit 2 | 3 | import android.content.Intent 4 | import android.graphics.Color 5 | import android.os.Bundle 6 | import android.util.Log 7 | import android.view.View 8 | import android.widget.Toast 9 | import androidx.appcompat.app.AppCompatActivity 10 | import androidx.lifecycle.Observer 11 | import androidx.lifecycle.ViewModelProvider 12 | import com.rkpandey.blogexplorer.MainActivity 13 | import com.rkpandey.blogexplorer.api.RetrofitInstance 14 | import com.rkpandey.blogexplorer.databinding.ActivityEditBinding 15 | import com.rkpandey.blogexplorer.detail.EXTRA_POST 16 | import com.rkpandey.blogexplorer.models.Post 17 | import kotlinx.coroutines.CoroutineScope 18 | import kotlinx.coroutines.Dispatchers 19 | import kotlinx.coroutines.launch 20 | 21 | private const val TAG = "EditActivity" 22 | class EditActivity : AppCompatActivity() { 23 | private lateinit var viewModel: EditViewModel 24 | private lateinit var binding: ActivityEditBinding 25 | 26 | override fun onCreate(savedInstanceState: Bundle?) { 27 | super.onCreate(savedInstanceState) 28 | binding = ActivityEditBinding.inflate(layoutInflater) 29 | setContentView(binding.root) 30 | createPost() 31 | 32 | val post = intent.getSerializableExtra(EXTRA_POST) as Post 33 | title = "Editing Post #${post.id}" 34 | binding.etTitle.setText(post.title) 35 | binding.etContent.setText(post.content) 36 | 37 | viewModel = ViewModelProvider(this).get(EditViewModel::class.java) 38 | viewModel.post.observe(this, Observer { updatedPost -> 39 | if (updatedPost == null) { 40 | binding.clPostResult.visibility = View.GONE 41 | return@Observer 42 | } 43 | binding.tvUpdatedTitle.text = updatedPost.title 44 | binding.tvUpdatedContent.text = updatedPost.content 45 | binding.clPostResult.visibility = View.VISIBLE 46 | }) 47 | viewModel.currentStatus.observe(this, Observer { currentStatus -> 48 | when (currentStatus) { 49 | ResultStatus.IDLE -> { 50 | binding.tvStatus.text = "Idle" 51 | binding.tvStatus.setTextColor(Color.GRAY) 52 | } 53 | ResultStatus.WORKING -> { 54 | binding.tvStatus.text = "Working..." 55 | binding.tvStatus.setTextColor(Color.MAGENTA) 56 | } 57 | ResultStatus.SUCCESS -> { 58 | binding.tvStatus.text = "Success!" 59 | binding.tvStatus.setTextColor(Color.GREEN) 60 | } 61 | ResultStatus.ERROR -> { 62 | binding.tvStatus.text = "Error :(" 63 | binding.tvStatus.setTextColor(Color.RED) 64 | } 65 | else -> { 66 | throw IllegalStateException("Unexpected result state found") 67 | } 68 | } 69 | }) 70 | viewModel.wasDeletionSuccessful.observe(this, Observer { wasDeletionSuccessful -> 71 | if (wasDeletionSuccessful) { 72 | Toast.makeText(this, "Deleted post successfully!", Toast.LENGTH_LONG).show() 73 | val intent = Intent(this, MainActivity::class.java) 74 | startActivity(intent) 75 | } 76 | }) 77 | 78 | binding.btnUpdatePut.setOnClickListener { 79 | Log.i(TAG, "Update via PUT") 80 | viewModel.updatePost(post.id, 81 | Post( 82 | post.userId, 83 | post.id, 84 | binding.etTitle.text.toString(), 85 | binding.etContent.text.toString() 86 | ) 87 | ) 88 | } 89 | 90 | binding.btnUpdatePatch.setOnClickListener { 91 | Log.i(TAG, "Update via PATCH") 92 | viewModel.patchPost(post.id, binding.etTitle.text.toString(), binding.etContent.text.toString()) 93 | } 94 | 95 | binding.btnDelete.setOnClickListener { 96 | Log.i(TAG, "DELETE") 97 | viewModel.deletePost(post.id) 98 | } 99 | } 100 | 101 | // Sample of how to create our own CoroutineScope to make network requests 102 | private fun createPost() { 103 | CoroutineScope(Dispatchers.IO).launch { 104 | val localNewPost = Post(2, 32, "My post title", "Body of post id #32") 105 | val newPost = RetrofitInstance.api.createPost(localNewPost) 106 | Log.i(TAG, "New post $newPost") 107 | val urlEncodedPost = 108 | RetrofitInstance.api.createPostUrlEncode(4, "New title", "Post content") 109 | Log.i(TAG, "URL encoded post: $urlEncodedPost") 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/edit/EditViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.edit 2 | 3 | import android.util.Log 4 | import androidx.lifecycle.LiveData 5 | import androidx.lifecycle.MutableLiveData 6 | import androidx.lifecycle.ViewModel 7 | import androidx.lifecycle.viewModelScope 8 | import com.rkpandey.blogexplorer.api.RetrofitInstance 9 | import com.rkpandey.blogexplorer.models.Post 10 | import kotlinx.coroutines.launch 11 | import java.lang.Exception 12 | 13 | private const val TAG = "EditViewModel" 14 | class EditViewModel : ViewModel() { 15 | private val _post: MutableLiveData = MutableLiveData() 16 | val post: LiveData 17 | get() = _post 18 | 19 | private val _currentStatus = MutableLiveData(ResultStatus.IDLE) 20 | val currentStatus: LiveData 21 | get() = _currentStatus 22 | 23 | private val _wasDeletionSuccessful = MutableLiveData(false) 24 | val wasDeletionSuccessful: LiveData 25 | get() = _wasDeletionSuccessful 26 | 27 | fun updatePost(postId: Int, newPostData: Post) { 28 | viewModelScope.launch { 29 | try { 30 | _post.value = null 31 | _currentStatus.value = ResultStatus.WORKING 32 | val updatedPost = RetrofitInstance.api.updatePost(postId, newPostData) 33 | Log.i(TAG, "updated post $updatedPost") 34 | _post.value = updatedPost 35 | _currentStatus.value = ResultStatus.SUCCESS 36 | } catch (e: Exception) { 37 | _currentStatus.value = ResultStatus.ERROR 38 | } 39 | } 40 | } 41 | 42 | fun patchPost(postId: Int, title: String, body: String) { 43 | viewModelScope.launch { 44 | try { 45 | _post.value = null 46 | _currentStatus.value = ResultStatus.WORKING 47 | val patchedPost = RetrofitInstance.api.patchPost(postId, mapOf("title" to title, "body" to body)) 48 | Log.i(TAG, "patched post $patchedPost") 49 | _post.value = patchedPost 50 | _currentStatus.value = ResultStatus.SUCCESS 51 | } catch (e: Exception) { 52 | _currentStatus.value = ResultStatus.ERROR 53 | } 54 | } 55 | } 56 | 57 | fun deletePost(postId: Int) { 58 | viewModelScope.launch { 59 | try { 60 | _currentStatus.value = ResultStatus.WORKING 61 | RetrofitInstance.api.deletePost("1234AuthToken", postId) 62 | _post.value = null 63 | _wasDeletionSuccessful.value = true 64 | _currentStatus.value = ResultStatus.SUCCESS 65 | } catch (e: Exception) { 66 | _currentStatus.value = ResultStatus.ERROR 67 | } 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/edit/ResultStatus.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.edit 2 | 3 | enum class ResultStatus { 4 | IDLE, 5 | WORKING, 6 | SUCCESS, 7 | ERROR 8 | } -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/models/Company.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.models 2 | 3 | import androidx.annotation.Keep 4 | 5 | @Keep 6 | data class Company(val name: String, val catchPhrase: String, val bs: String) -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/models/Post.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.models 2 | 3 | import androidx.annotation.Keep 4 | import com.squareup.moshi.Json 5 | import java.io.Serializable 6 | 7 | @Keep 8 | data class Post( 9 | val userId: Int, 10 | val id: Int, 11 | val title: String, 12 | @Json(name = "body") val content: String): Serializable -------------------------------------------------------------------------------- /app/src/main/java/com/rkpandey/blogexplorer/models/User.kt: -------------------------------------------------------------------------------- 1 | package com.rkpandey.blogexplorer.models 2 | 3 | import androidx.annotation.Keep 4 | 5 | @Keep 6 | data class User( 7 | val id: Int, 8 | val name: String, 9 | val username: String, 10 | val email: String, 11 | val company: Company, 12 | val website: String 13 | ) -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 15 | 16 | 24 | 25 | 35 | 36 | 45 | 46 | 54 | 55 | 65 | 66 | 75 | 76 | 86 | 87 | 97 | 98 | 108 | 109 | 118 | 119 | 129 | 130 | 139 | 140 | 149 | 150 | 151 | 152 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_edit.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 21 | 22 | 36 | 37 |