├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── _config.yml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── arcane │ │ └── coldstorage │ │ ├── MainActivity.kt │ │ ├── application │ │ └── Application.kt │ │ └── cache │ │ ├── CacheWithFreeze.kt │ │ ├── CacheWithFreezeWithCustomName.kt │ │ ├── CacheWithRefrigerate.kt │ │ └── ImageCache.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ ├── ic_launcher_background.xml │ └── test_load.xml │ ├── layout │ └── activity_main.xml │ ├── menu │ └── menu_main.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── coldstorageannotation ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── arcane │ └── coldstorageannotation │ ├── CacheKey.kt │ ├── Freeze.kt │ ├── LoadImage.kt │ ├── Parent.kt │ └── Refrigerate.kt ├── coldstoragecache ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── arcane │ │ │ └── coldstoragecache │ │ │ ├── .gitkeep │ │ │ ├── cache │ │ │ ├── Cache.kt │ │ │ └── ColdStorage.kt │ │ │ ├── callback │ │ │ ├── OnOperationSuccessfulCallback.kt │ │ │ └── OnValueFetchedCallback.kt │ │ │ ├── converter │ │ │ ├── IConverter.kt │ │ │ └── impl │ │ │ │ └── StringToBitmapConverter.kt │ │ │ ├── helper │ │ │ ├── BindHelper.kt │ │ │ ├── CommonHelper.kt │ │ │ ├── ImageHelper.kt │ │ │ └── StorageHelper.kt │ │ │ └── model │ │ │ ├── CachedDataModel.kt │ │ │ ├── ColdStorageModel.kt │ │ │ ├── ImageMetadata.kt │ │ │ └── LoadImageConfig.kt │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── arcane │ └── coldstoragecache │ └── cache │ ├── CacheTest.kt │ └── ColdStorageTest.kt ├── coldstoragecompiler ├── .gitignore ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── arcane │ │ └── coldstoragecompiler │ │ ├── AnnotationProcessor.kt │ │ ├── FreezeAnnotationProcessor.kt │ │ ├── LoadImageProcessor.kt │ │ └── helper │ │ └── CodeGenerationHelper.kt │ └── test │ └── java │ └── com │ └── arcane │ └── coldstoragecompiler │ └── AnnotationProcessorTest.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | android: 3 | components: 4 | - android-29 5 | - build-tools-29.0.2 6 | licenses: 7 | - 'android-sdk-license-.+' 8 | - '.+' 9 | 10 | env: 11 | global: 12 | # install timeout in minutes (2 minutes by default) 13 | - ADB_INSTALL_TIMEOUT=8 14 | 15 | before_install: 16 | - touch $HOME/.android/repositories.cfg 17 | - yes | sdkmanager "platforms;android-29" 18 | - yes | sdkmanager "build-tools;29.0.2" 19 | 20 | #Allow travis to use gradlew 21 | before_script: 22 | - chmod +x gradlew 23 | 24 | before_cache: 25 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 26 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 27 | cache: 28 | directories: 29 | - $HOME/.gradle/caches/ 30 | - $HOME/.gradle/wrapper/ 31 | - $HOME/.android/build-cache 32 | 33 | # Run assemble and unit tests 34 | script: 35 | - ./gradlew clean assembleDebug assembleRelease testDebug 36 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Crypticmindscom@outlook.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # ColdStorage 3 |

4 | 5 |

6 | 7 | **A lightweight data loading and caching library for android** 8 | 9 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ![Downloads](https://jitpack.io/v/crypticminds/ColdStorage/month.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/946075aa2cc14be3af73eb8a9fc2352b)](https://www.codacy.com/manual/crypticminds/ColdStorage?utm_source=github.com&utm_medium=referral&utm_content=crypticminds/ColdStorage&utm_campaign=Badge_Grade) [![Build Status](https://travis-ci.com/crypticminds/ColdStorage.svg?branch=master)](https://travis-ci.com/crypticminds/ColdStorage) [![Gitter](https://badges.gitter.im/ColdStorageCache/community.svg)](https://gitter.im/ColdStorageCache/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 10 | 11 | # Quicklinks 12 | 13 | * [**Feature requests**](https://github.com/crypticminds/ColdStorage/issues/new?assignees=&labels=&template=feature_request.md&title=): Got a new requirement? Request it here and it will be delivered. 14 | * [**Bugs**](https://github.com/crypticminds/ColdStorage/issues/new?assignees=&labels=&template=bug_report.md&title=): Report a bug here and it will be squashed. 15 | * [**Questions**](https://gitter.im/ColdStorageCache/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge): Get your questions about contributing, usage or anything related to the library answered here. 16 | * [**Examples**](https://github.com/crypticminds/coldstorageexamples) : Check out various examples here. 17 | * [**Suggestions/Complaints/Feedbacks**](https://github.com/crypticminds/ColdStorage/issues/new): Got something in your mind regarding this library? Please share and help us improve. 18 | * [**Upcoming features**](https://github.com/crypticminds/ColdStorage/wiki/Upcoming-features) : If you are interested to see all the exciting features lined up for delivery. 19 | 20 | # Articles 21 | * [Caching in general](https://medium.com/@crypticmindscom_5258/caching-made-easy-with-kotlin-part-1-53433c756978) 22 | * [@Refrigerate annotation usage](https://medium.com/@crypticmindscom_5258/caching-made-easy-in-android-with-kotlin-part-2-61bb476063b4) 23 | * [@Freeze annotation usage](https://medium.com/@crypticmindscom_5258/caching-made-easy-on-android-with-kotlin-part-3-3d4cfcb57df0) 24 | * [@LoadImage annotation usage](https://medium.com/@crypticmindscom_5258/caching-made-easy-on-android-with-kotlin-part-4-18e7b066e9c2) 25 | # Setup 26 | 27 | ## Latest version ![Release](https://jitpack.io/v/crypticminds/ColdStorage.svg) 28 | 29 | * Add kotlin-kapt gradle plugin to **app build.gradle** file 30 | 31 | apply plugin: "kotlin-kapt" 32 | 33 | * Add the dependencies 34 | 35 | ``` 36 | implementation "com.github.crypticminds.ColdStorage:coldstoragecache:{enter latest version}" 37 | kapt "com.github.crypticminds.ColdStorage:coldstoragecompiler:{enter latest version}" 38 | implementation "com.github.crypticminds.ColdStorage:coldstorageannotation:{enter latest version}" 39 | 40 | ``` 41 | 42 | **You need to initialize the cache when the application starts. The initialization takes care of pulling previously cached data and loading them into the memory .** 43 | 44 | * Create an application class and initialize the cache in the onCreate() method. 45 | 46 | ```kotlin 47 | import android.app.Application 48 | import com.arcane.coldstoragecache.cache.Cache 49 | 50 | class Application : Application() { 51 | 52 | override fun onCreate() { 53 | super.onCreate() 54 | Cache.initialize(context = applicationContext) 55 | } 56 | } 57 | ``` 58 | You can configure the cache with additional parameters such as a global time to live, maximum cache size etc. Refer the [wiki]([https://github.com/crypticminds/ColdStorage/wiki/Initialize-cache](https://github.com/crypticminds/ColdStorage/wiki/Initialize-cache)) for more details. 59 | 60 | * Register your application in the android manifest file by providing the **android:name** attribute 61 | 62 | ```xml 63 | 71 | 72 | # Quick guide 73 | 74 | ### This guide will only provide a basic usage guide. For detailed description of each component, usage and examples check the [wiki](https://github.com/crypticminds/ColdStorage/wiki) 75 | 76 | ## @LoadImage Annotation 77 | 78 | You can annotate any ImageView present in an Activity , fragement or another view to load images from an URL and cache it for future use. 79 | 80 | ```kotlin 81 | @LoadImage( 82 | R.id.image_1, 83 | "https://images.unsplash.com/photo-1549740425-5e9ed4d8cd34?ixlib=rb-1.2.1&w=1000&q=80", 84 | placeHolder = R.drawable.loading, enableLoadingAnimation = true, persistImageToDisk = true 85 | ) 86 | lateinit var imageWithAnimation: ImageView 87 | ``` 88 | 89 | Images can be persisted into the internal storage using the **"persistImageToDisk"** parameter. 90 | 91 | After the image views have been annotated , bind the class where the image views are present using the method **Cache.bind(object).** 92 | 93 | You can pass the activity, fragement or the view to which the annotated ImageViews belong to. 94 | 95 | In an activity, the method should be called after setContentView and in a fragemnt it should be called in **onViewCreated** method. 96 | 97 | ```kotlin 98 | override fun onCreate(savedInstanceState: Bundle?) { 99 | super.onCreate(savedInstanceState) 100 | setContentView(R.layout.load_image_example) 101 | Cache.bind(this) 102 | } 103 | ``` 104 | 105 | Currently the cache can only be bound to an Activity , fragment or view. 106 | 107 | ## @Parent Annotation 108 | 109 | An annotation that helps binding a nested view to a resource id. 110 | Suppose you have a layout **layout_1.xml** which contains an ImageView. You have added this layout in your main layout using the 111 | **** tag.You can now use @LoadImage annotation on the ImageView by : 112 | 113 | * Provide an id to the include tag 114 | 115 | ```xml 116 | 120 | ``` 121 | 122 | * Use Parent annotation along with LoadImage annotation 123 | 124 | ```kotlin 125 | @Parent(R.id.my_included_layout) 126 | @LoadImage(R.id.my_nested_image_view,"http://url.jpg" 127 | lateinit var childImageView : ImageView 128 | ``` 129 | 130 | ## @Freeze Annotation 131 | 132 | Annotate your class using the freeze annotation to apply caching logic on top of all the public methods present in the class. 133 | 134 | ```kotlin 135 | @Freeze(generatedClassName = "MyBeautifulCacheLayer") 136 | class MakeRemoteCallWithFreeze { 137 | 138 | 139 | fun makeRemoteCallToServiceA(value: String): String { 140 | val url = "https://httpbin.org/get?param1=$value" 141 | val textResponse = URL(url).readText() 142 | return textResponse 143 | } 144 | 145 | 146 | /** 147 | * Here I am marking the parameters that will together form the cache key 148 | * with @CacheKey 149 | */ 150 | fun makeRemoteCallToServiceB( 151 | @CacheKey parameter1: String, 152 | @CacheKey parameter2: String, 153 | parameter3: String 154 | ): String { 155 | val url = "https://httpbin.org/get?param1=$parameter1¶m2=$parameter2¶m3=$parameter3" 156 | val textResponse = URL(url).readText() 157 | return textResponse 158 | } 159 | } 160 | ``` 161 | This will generate a class called "**MyBeautifulCacheLayer**" . You can use this class to call the methods. 162 | ```kotlin 163 | //you need to implement the OnOperationSuccessfulCallback interface. 164 | val callback = object : OnOperationSuccessfulCallback{ 165 | override fun onSuccess(output: String?, operation: String) { 166 | //handle the output here. 167 | //operation is the name of the method that returns the output. In this case the output 168 | //can be "makeRemoteCallToServiceB" or "makeRemoteCallToServiceA" . You can handle the output 169 | //based on which method is returning it. 170 | } 171 | } 172 | 173 | val cacheLayer = MyBeautifulCacheLayer() 174 | 175 | cacheLayer.makeRemoteCallToServiceA("someString" , callback) 176 | 177 | cacheLayer.makeRemoteCallToServiceB(.... ) 178 | 179 | ``` 180 | ## @Refrigerate Annotation 181 | Annotate your functions with refrigerate to cache the output of the function for a given set of inputs. 182 | 183 | ```kotlin 184 | @Refrigerate(timeToLive : 2000, operation = "cacheImage") 185 | fun downloadImage(@CacheKey url : String , @CacheKey data : String , variableThatIsNotAKey : String) : Bitmap { 186 | ..... 187 | } 188 | ``` 189 | This will keep the bitmap in the cache for 2 seconds. 190 | 191 | In the above example **url** and **data** will together form the key of the cache , such that if it determines that the same url and data is passed to the function (until the value expires in the cache) irrespective of the value of "**variableThatIsNotAKey**" it will 192 | return the data from the cache. 193 | 194 | During compilation the annotations will generate a class "**GeneratedCacheLayer** 195 | and instead of using your annotated functions directly you will use them via this class. 196 | 197 | To invoke the above functions you will call :- 198 | 199 | ```kotlin 200 | GeneratedCacheLayer.downloadImage("myurl", objectOfTheClassWhereTheMethodBelongs , callback) 201 | 202 | GeneratedCacheLayer.callRemoteService("myurl", "mydata" , "myrandomVariable" , objectOfTheClassWhereTheMethodBelongs , callback) 203 | ``` 204 | 205 | The generated method will have the same name and accept the same variables as the original method but with two extra parameters , one is the object of the class where the original annotated method is present in and the second is the callback (**OnOperationsuccessfulCallback**) which will be used to pass the cached data to the main thread from the background thread. 206 | 207 | ## Create a custom cache layer 208 | 209 | Create your cache layer by extending the **Cache class**. You will have to implement the update method. 210 | The update method should take care of fetching the data when the data is stale or is not present in the cache. 211 | 212 | ```kotlin 213 | import android.graphics.Bitmap 214 | import android.graphics.BitmapFactory 215 | import android.util.Base64 216 | import android.util.Log 217 | import com.arcane.coldstoragecache.cache.Cache 218 | import java.io.ByteArrayOutputStream 219 | import java.net.URL 220 | 221 | 222 | /** 223 | * An example class that is used to cache images 224 | * after downloading them from a given url. 225 | * 226 | */ 227 | class ImageCache : Cache() { 228 | 229 | /** 230 | * The update function is only required here to specify 231 | * where to fetch the data from if the key is not present in the 232 | * cache. 233 | * 234 | * @param key Here the key is the url from where the 235 | * image needs to be downloaded. 236 | */ 237 | override fun update(key: String): String? { 238 | return try { 239 | val url = URL(key) 240 | val connection = url.openConnection() 241 | connection.doInput = true 242 | connection.connect() 243 | val input = connection.getInputStream() 244 | val myBitmap = BitmapFactory.decodeStream(input) 245 | bitMapToString(myBitmap) 246 | } catch (e: Exception) { 247 | Log.e("EXCEPTION", "Unable to download image", e) 248 | return null 249 | } 250 | } 251 | 252 | /** 253 | * A transformer to convert the bitmap to string. 254 | */ 255 | private fun bitMapToString(bitmap: Bitmap): String? { 256 | val baos = ByteArrayOutputStream() 257 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos) 258 | val b: ByteArray = baos.toByteArray() 259 | return Base64.encodeToString(b, Base64.DEFAULT) 260 | } 261 | } 262 | ``` 263 | 264 | **The update method should return the value to be cached in form of a string. If you are planning to store complex objects , serialize them into a string and return them from the method.** 265 | 266 | Your cache is now ready. To use the cache create an instance of it and call the **get** method of the cache. 267 | 268 | The get method accepts the key that needs to be fetched from the cache and a callback which will be used to return the result to the main thread. **The cache performs all operations in a background thread and will never block the UI thread.** 269 | You will need to implement the **OnValueFetchedCallback** interface and pass it to the **get** method of the cache. The cache will fetch the value and pass it to the callback method from where you can access it and use in the UI thread. 270 | 271 | Optionally you can also pass a time to live value and a converter. They are explained in detail below. 272 | 273 | ```kotlin 274 | import android.graphics.Bitmap 275 | import android.os.Bundle 276 | import android.view.Menu 277 | import android.view.MenuItem 278 | import android.widget.Button 279 | import android.widget.ImageView 280 | import androidx.appcompat.app.AppCompatActivity 281 | import com.arcane.coldstorage.cache.ImageCache 282 | import com.arcane.coldstoragecache.callback.OnValueFetchedCallback 283 | import com.arcane.coldstoragecache.converter.impl.StringToBitmapConverter 284 | 285 | class MainActivity : AppCompatActivity(), OnValueFetchedCallback { 286 | 287 | companion object { 288 | val URLS = arrayListOf( 289 | "https://images.unsplash.com/photo-1452857297128-d9c29adba80b?ixlib=rb-1.2.1&w=1000&q=80", 290 | "https://i.ytimg.com/vi/Pc20_oJQusc/maxresdefault.jpg", 291 | "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS1HHodR1IgMESyE95LqwLRTRFnfCpmKKw5RQHqnP_kWV9ugKaiIQ&s" 292 | ) 293 | } 294 | 295 | /** 296 | * An instance of image cache. 297 | */ 298 | private val imageCache: ImageCache = ImageCache() 299 | 300 | /** 301 | * The image view where the images will be displayed. 302 | */ 303 | private lateinit var imageView: ImageView 304 | 305 | /** 306 | * The button used to change the image. 307 | */ 308 | private lateinit var changeButton: Button 309 | 310 | override fun onCreate(savedInstanceState: Bundle?) { 311 | super.onCreate(savedInstanceState) 312 | setContentView(R.layout.activity_main) 313 | imageView = findViewById(R.id.image_view) 314 | changeButton = findViewById(R.id.change) 315 | checkImageCaching() 316 | changeButton.setOnClickListener { 317 | checkImageCaching() 318 | } 319 | } 320 | 321 | /** 322 | * Method to test image caching. 323 | */ 324 | private fun checkImageCaching() { 325 | val converter = StringToBitmapConverter() 326 | imageCache.get( 327 | URLS.shuffled().take(1)[0], 328 | this, 329 | converter 330 | ) 331 | 332 | } 333 | 334 | /** 335 | * When the image is downloaded , adding the image to 336 | * the image view. 337 | */ 338 | override fun valueFetched(output: Any?) { 339 | imageCache.commitToSharedPref(applicationContext) 340 | runOnUiThread { 341 | val outputAsBitmap = output as Bitmap 342 | imageView.setImageBitmap(outputAsBitmap) 343 | } 344 | } 345 | } 346 | 347 | ``` 348 | 349 | **The time to live value in the get method to specify how long a data needs to be stored in the cache.** 350 | 351 | **The converter object takes care of deserializing the string into the object you need. It is an optional parameter. If the converter is not passed the cache will return the value as string.** 352 | 353 | # License 354 | ``` 355 | Copyright 2020 Anurag Mandal 356 | 357 | Licensed under the Apache License, Version 2.0 (the "License"); 358 | you may not use this file except in compliance with the License. 359 | You may obtain a copy of the License at 360 | 361 | http://www.apache.org/licenses/LICENSE-2.0 362 | 363 | Unless required by applicable law or agreed to in writing, software 364 | distributed under the License is distributed on an "AS IS" BASIS, 365 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 366 | See the License for the specific language governing permissions and 367 | limitations under the License. 368 | ``` 369 | 370 | ## Author 371 | 372 | Anurag Mandal [LinkedIn]( https://www.linkedin.com/in/anurag-mandal-86a65b164/) 373 | 374 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | apply plugin: 'kotlin-kapt' 8 | 9 | android { 10 | compileSdkVersion 29 11 | buildToolsVersion "29.0.2" 12 | compileSdkVersion 29 13 | buildToolsVersion "29.0.2" 14 | defaultConfig { 15 | applicationId "com.arcane.coldstorage" 16 | minSdkVersion 15 17 | targetSdkVersion 29 18 | versionCode 1 19 | versionName "1.0" 20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 21 | } 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | } 29 | 30 | dependencies { 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 33 | implementation 'androidx.appcompat:appcompat:1.0.2' 34 | implementation 'androidx.core:core-ktx:1.0.2' 35 | 36 | implementation 'com.squareup.picasso:picasso:2.71828' 37 | 38 | 39 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 40 | implementation 'com.google.android.material:material:1.0.0' 41 | testImplementation 'junit:junit:4.12' 42 | androidTestImplementation 'androidx.test.ext:junit:1.1.0' 43 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 44 | androidTestImplementation 'org.mockito:mockito-core:2.19.0' 45 | implementation project(path: ':coldstoragecache') 46 | implementation project(path: ':coldstorageannotation') 47 | kapt project(path: ':coldstoragecompiler') 48 | 49 | } 50 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 15 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/src/main/java/com/arcane/coldstorage/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.arcane.coldstorage 2 | 3 | import android.content.Intent 4 | import android.graphics.Bitmap 5 | import android.os.Bundle 6 | import android.view.Menu 7 | import android.view.MenuItem 8 | import android.widget.Button 9 | import android.widget.ImageView 10 | import androidx.appcompat.app.AppCompatActivity 11 | import com.arcane.coldstorage.cache.ImageCache 12 | import com.arcane.coldstorageannotation.LoadImage 13 | import com.arcane.coldstoragecache.cache.Cache 14 | import com.arcane.coldstoragecache.callback.OnValueFetchedCallback 15 | import com.squareup.picasso.Picasso 16 | 17 | /** 18 | * The main activity for the example app. 19 | * This shows the example of @LoadImage annotation. 20 | * 21 | * @author Anurag 22 | */ 23 | class MainActivity : AppCompatActivity(), OnValueFetchedCallback { 24 | 25 | 26 | /** 27 | * An instance of image cache. 28 | */ 29 | private val imageCache: ImageCache = ImageCache() 30 | 31 | /** 32 | * The image view where the images will be displayed. 33 | */ 34 | @LoadImage( 35 | R.id.image_view, 36 | "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS-GsnyKLBNYVfl0Uuq-PGreWRTwdAIRGL_BOtG24SayIS9HDwq&s" 37 | ) 38 | lateinit var imageView: ImageView 39 | 40 | @LoadImage( 41 | R.id.image_view_2, 42 | "https://images.unsplash.com/photo-1485550409059-9afb054cada4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80", 43 | R.drawable.test_load, 44 | enableLoadingAnimation = true, 45 | persistImageToDisk = true 46 | ) 47 | lateinit var imageView2: ImageView 48 | 49 | // @LoadImage("https://www.ddfl.org/wp-content/uploads/2018/03/bunnies-easter.png") 50 | lateinit var imageView3: ImageView 51 | 52 | 53 | override fun onCreate(savedInstanceState: Bundle?) { 54 | super.onCreate(savedInstanceState) 55 | setContentView(R.layout.activity_main) 56 | imageView3 = findViewById(R.id.imageView2) 57 | 58 | 59 | Cache.bind(this) 60 | 61 | Picasso.get() 62 | .load("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS-GsnyKLBNYVfl0Uuq-PGreWRTwdAIRGL_BOtG24SayIS9HDwq&s") 63 | .into(imageView3) 64 | 65 | findViewById