Repository: MarcinMoskala/PreferenceHolder
Branch: master
Commit: 6d5819131ed5
Files: 62
Total size: 88.9 KB
Directory structure:
gitextract_ryqsddrd/
├── .codebeatignore
├── .gitignore
├── .travis.yml
├── LICENSE
├── LICENSE.txt
├── README.md
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── preferenceholder/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── marcinmoskala/
│ │ └── kotlinpreferences/
│ │ ├── BaseTest.kt
│ │ ├── CleaningTest.kt
│ │ ├── ExampleConfig.kt
│ │ ├── PreferenceFieldNullableTest.kt
│ │ ├── PreferenceFieldTest.kt
│ │ └── TestUtills.kt
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── marcinmoskala/
│ └── kotlinpreferences/
│ ├── PreferenceHolder.kt
│ ├── PreferenceHolderApplication.kt
│ ├── Serializer.kt
│ ├── TypeToken.kt
│ └── bindings/
│ ├── Clearable.kt
│ ├── Errors.kt
│ ├── GetKey.kt
│ ├── PreferenceFieldBinder.kt
│ ├── PreferenceFieldBinderCaching.kt
│ ├── PreferenceFieldBinderNullable.kt
│ ├── PreferenceFieldBinderNullableCaching.kt
│ └── PutValueExt.kt
├── preferenceholder-gson-serializer/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── marcinmoskala/
│ │ └── kotlinpreferences/
│ │ ├── DeserializationTest.kt
│ │ ├── GsonBaseTest.kt
│ │ ├── TestUtills.kt
│ │ ├── collections/
│ │ │ ├── CollectionsConfig.kt
│ │ │ └── CollectionsTest.kt
│ │ ├── issue2test/
│ │ │ └── Issue2Test.kt
│ │ └── objects/
│ │ ├── ObjectConfig.kt
│ │ └── ObjectsTest.kt
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── marcinmoskala/
│ └── kotlinpreferences/
│ └── gson/
│ └── GsonSerializer.kt
├── sample/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── marcinmoskala/
│ │ └── testapp/
│ │ ├── DefaultChangeTest.kt
│ │ ├── ExampleConfig.kt
│ │ ├── NullableChangeTest.kt
│ │ └── NullableClassesChangeTest.kt
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── com/
│ │ └── marcinmoskala/
│ │ └── testapp/
│ │ ├── MainActivity.kt
│ │ └── Pref.kt
│ └── res/
│ ├── layout/
│ │ └── activity_main.xml
│ └── values/
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .codebeatignore
================================================
preferenceholder-lib/src/androidTest/**
preferenceholder-lib/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolder.kt
preferenceholder-lib/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolderApplication.kt
sample/**
================================================
FILE: .gitignore
================================================
*.iml
.gradle
/local.properties
/.idea/*
.DS_Store
/build
/captures
.externalNativeBuild
================================================
FILE: .travis.yml
================================================
language: android
jdk: oraclejdk8
android:
components:
- tools
- platform-tools
- build-tools-27.0.1
- android-27
- android-22
- extra-android-m2repository
- sys-img-armeabi-v7a-android-22
jdk:
- oraclejdk8
sudo: true
before_script:
- echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a
- emulator -avd test -no-skin -no-audio -no-window &
- android-wait-for-emulator
- sleep 10
- adb shell input keyevent 82
env:
matrix:
- TEST=:preferenceholder:connectedDebugAndroidTest
- TEST=:preferenceholder-gson-serializer:connectedDebugAndroidTest
script:
- ./gradlew $TEST -i
branches:
only:
- master
- stable
cache:
directories:
- $HOME/.m2
- $HOME/.gradle
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: LICENSE.txt
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# PreferenceHolder
Kotlin Android Library, that makes preference usage simple and fun.
[](https://jitpack.io/#com.MarcinMoskala/PreferenceHolder)[](http://www.apache.org/licenses/LICENSE-2.0)
[](https://travis-ci.org/MarcinMoskala/PreferenceHolder)
[](https://codebeat.co/projects/github-com-marcinmoskala-preferenceholder-master)
[](https://github.com/MarcinMoskala/PreferenceHolder)
[](https://github.com/MarcinMoskala/PreferenceHolder)
To stay up-to-date with news about library [](https://twitter.com/marcinmoskala?ref_src=twsrc%5Etfw)
This library is younger brother of [KotlinPreferences](https://github.com/MarcinMoskala/KotlinPreferences).
With PreferenceHolder, you can define different preference fields this way:
```kotlin
object Pref: PreferenceHolder() {
var canEatPie: Boolean by bindToPreferenceField(true)
}
```
And use it this way:
```kotlin
if(Pref.canEatPie) //...
```
Here are other preference definition examples: (see [full example](https://github.com/MarcinMoskala/PreferenceHolder/blob/master/kotlinpreferences-lib/src/androidTest/java/com/marcinmoskala/kotlinpreferences/ExampleConfig.kt) and [usage](https://github.com/MarcinMoskala/PreferenceHolder/tree/master/kotlinpreferences-lib/src/androidTest/java/com/marcinmoskala/kotlinpreferences))
```kotlin
object UserPref: PreferenceHolder() {
var canEatPie: Boolean by bindToPreferenceField(true)
var allPieInTheWorld: Long by bindToPreferenceField(0)
var isMonsterKiller: Boolean? by bindToPreferenceFieldNullable()
var monstersKilled: Int? by bindToPreferenceFieldNullable()
// Property with backup is reading stored value in the first usage,
// and saving it, in background, each time it is changed.
var experience: Float? by bindToPropertyWithBackup(-1.0F)
var className: String? by bindToPropertyWithBackupNullable()
// Any type can used if serializer is set. See: Gson serialization
var character: Character? by bindToPreferenceFieldNullable()
var savedGame: Game? by bindToPreferenceFieldNullable()
// Single level collections are also supported if serializer is set. See: Gson serialization
var longList: Map<Int, Long> by bindToPreferenceField(mapOf(0 to 12L, 10 to 143L))
var propTest: List<Character>? by bindToPropertyWithBackupNullable()
var elemTest: Set<Elems> by bindToPreferenceField(setOf(Elems.Elem1, Elems.Elem3))
}
```
There must be application Context added to PreferenceHolder companion object. Example:
```kotlin
class App : Application() {
override fun onCreate() {
super.onCreate()
PreferenceHolder.setContext(applicationContext)
}
}
```
It it suggested to do it in project Application class. As an alternative, PreferenceHolderApplication can also be added as a name of an application in AndroidManifest: ([example](https://github.com/MarcinMoskala/PreferenceHolder/blob/master/sample/src/main/AndroidManifest.xml#L12))
```
android:name="com.marcinmoskala.kotlinpreferences.PreferenceHolderApplication"
```
## Unit testing components
Library also include test mode:
```
PreferenceHolder.testingMode = true
```
When it is turned on, then all properties are acting just like normal properties without binding to preference field. This allows to make unit tests to presenters and to use cases that are using instance of PreferenceHolder.
## Install
To add PreferenceHolder to the project, add to build.gradle file:
```groovy
dependencies {
compile "com.marcinmoskala.PreferenceHolder:preferenceholder:1.51"
}
```
While library is located on JitPack, remember to add to module build.gradle (unless you already have it):
```groovy
repositories {
maven { url 'https://jitpack.io' }
}
```
## Gson serialization
To use Gson serializer, we need to add following dependency:
```groovy
dependencies {
compile "com.marcinmoskala.PreferenceHolder:preferenceholder-gson-serializer:1.51"
}
```
And specify `GsonSerializer` as `PreferenceHolder` serializer:
```kotlin
PreferenceHolder.serializer = GsonSerializer(Gson())
```
Since then, we can use all types, even one not supported by SharedPreference (like custom objects `Character` and `Game`, or collections)
## Other libraries
If you like it, remember to leave the star and check out my other libraries:
* [ActivityStarter](https://github.com/MarcinMoskala/ActivityStarter/blob/master/README.md) - Simple Android Library, that provides easy way to start and save state of Activities, Fragments, Services and Receivers with arguments.
* [ArcSeekBar](https://github.com/MarcinMoskala/ArcSeekBar) - Good looking curved Android SeekBar
* [VideoPlayView](https://github.com/MarcinMoskala/VideoPlayView) - Custom Android view with video player, loader and placeholder image
* [KotlinAndroidViewBindings](https://github.com/MarcinMoskala/KotlinAndroidViewBindings) - Bindings for properties with simple Kotlin types (Boolean, String) to layout traits (visibility, text).
License
-------
Copyright 2017 Marcin Moskała
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: build.gradle
================================================
buildscript {
ext.kotlin_version = '1.2.0-rc-84'
repositories {
google()
jcenter()
maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.2" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.2" }
}
}
repositories {
mavenCentral()
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Tue Nov 28 16:54:24 CET 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: preferenceholder/.gitignore
================================================
/build
================================================
FILE: preferenceholder/build.gradle
================================================
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'com.github.dcendents.android-maven'
group='com.marcinmoskala'
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
minSdkVersion 14
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
// Fancy test print
tasks.withType(Test) {
testLogging {
// set options for log level LIFECYCLE
events "passed", "skipped", "failed", "standardOut"
showExceptions true
exceptionFormat "full"
showCauses true
showStackTraces true
// set options for log level DEBUG and INFO
debug {
events "started", "passed", "skipped", "failed", "standardOut", "standardError"
exceptionFormat "full"
}
info.events = debug.events
info.exceptionFormat = debug.exceptionFormat
afterSuite { desc, result ->
if (!desc.parent) { // will match the outermost suite
def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
def startItem = '| ', endItem = ' |'
def repeatLength = startItem.length() + output.length() + endItem.length()
println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
}
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
install {
repositories.mavenInstaller {
pom.project {
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
}
}
}
================================================
FILE: preferenceholder/proguard-rules.pro
================================================
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/BaseTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.InstrumentationRegistry
open class BaseTest {
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
PreferenceHolder.serializer = null
TestPreferences.clear()
}
}
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/CleaningTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.TestPreferences.className
import com.marcinmoskala.kotlinpreferences.TestPreferences.experience
import com.marcinmoskala.kotlinpreferences.TestPreferences.isMonsterKiller
import com.marcinmoskala.kotlinpreferences.TestPreferences.monstersKilled
import com.marcinmoskala.kotlinpreferences.TestPreferences.numberOfHahaInLough
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CleaningTest: BaseTest() {
@Test
fun afterCleaningPropertiesAreSetToDefaultTest() {
TestPreferences.canEatPie = false
TestPreferences.pieBaked = 1000
TestPreferences.allPieInTheWorld = 9090
TestPreferences.pieEaten = 190F
TestPreferences.bestPieName = "Marcin"
TestPreferences.clear()
assertEquals(true, TestPreferences.canEatPie)
assertEquals(5, TestPreferences.pieBaked)
assertEquals(-1L, TestPreferences.allPieInTheWorld)
assertEquals(0.0F, TestPreferences.pieEaten)
assertEquals("Pie", TestPreferences.bestPieName)
}
@Test
fun afterCleaningNullablePropertiesAreSetToNullTest() {
TestPreferences.isMonsterKiller = false
TestPreferences.monstersKilled = 1000
TestPreferences.numberOfHahaInLough = 9090
TestPreferences.experience = 190F
TestPreferences.className = "Marcin"
TestPreferences.clear()
assertEquals(null, isMonsterKiller)
assertEquals(null, monstersKilled)
assertEquals(null, numberOfHahaInLough)
assertEquals(null, experience)
assertEquals(null, className)
}
@Test
fun cleaningIsOnlyApplyedToSinglePrefClass() {
TestPreferences.isMonsterKiller = false
TestPreferences.monstersKilled = 1000
assertEquals(false, isMonsterKiller)
assertEquals(1000, monstersKilled)
}
}
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/ExampleConfig.kt
================================================
package com.marcinmoskala.kotlinpreferences
object TestPreferences: PreferenceHolder() {
var canEatPie: Boolean by bindToPreferenceField(true)
var pieBaked: Int by bindToPreferenceField(5)
var allPieInTheWorld: Long by bindToPreferenceField(-1L)
var pieEaten: Float by bindToPreferenceField(0.0F)
var bestPieName: String by bindToPreferenceField("Pie")
var isMonsterKiller: Boolean? by bindToPreferenceFieldNullable()
var monstersKilled: Int? by bindToPreferenceFieldNullable()
var numberOfHahaInLough: Long? by bindToPreferenceFieldNullable()
var experience: Float? by bindToPreferenceFieldNullable()
var className: String? by bindToPreferenceFieldNullable()
}
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/PreferenceFieldNullableTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.TestPreferences.className
import com.marcinmoskala.kotlinpreferences.TestPreferences.experience
import com.marcinmoskala.kotlinpreferences.TestPreferences.isMonsterKiller
import com.marcinmoskala.kotlinpreferences.TestPreferences.monstersKilled
import com.marcinmoskala.kotlinpreferences.TestPreferences.numberOfHahaInLough
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PreferenceFieldNullableTest: BaseTest() {
@Test
fun booleanDefaultChangeTest() {
testValues(TestPreferences::isMonsterKiller, null, true, false, true, null)
}
@Test
fun intDefaultChangeTest() {
testValues(TestPreferences::monstersKilled, null, 10, 0, 10, -19)
}
@Test
fun longDefaultChangeTest() {
testValues(TestPreferences::numberOfHahaInLough, null, 10L, 0L, 100L)
}
@Test
fun floatDefaultChangeTest() {
testValues(TestPreferences::experience, null, 10F, 0F, 100F)
}
@Test
fun stringDefaultChangeTest() {
testValues(TestPreferences::className, null, "BlueberryPie", "SuperPie")
}
}
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/PreferenceFieldTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PreferenceFieldTest: BaseTest() {
@Test
fun booleanDefaultChangeTest() {
testValues(TestPreferences::canEatPie, true, false, true, false)
}
@Test
fun intDefaultChangeTest() {
testValues(TestPreferences::pieBaked, 5, 10, 0, 10, -19)
}
@Test
fun longDefaultChangeTest() {
testValues(TestPreferences::allPieInTheWorld, -1L, 10L, 0L, 100L)
}
@Test
fun floatDefaultChangeTest() {
testValues(TestPreferences::pieEaten, 0.0F, 10F, 0.06F, 100F)
}
@Test
fun stringDefaultChangeTest() {
testValues(TestPreferences::bestPieName, "Pie", "BlueberryPie", "SuperPie")
}
}
================================================
FILE: preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/TestUtills.kt
================================================
package com.marcinmoskala.kotlinpreferences
import org.junit.Assert
import kotlin.reflect.KMutableProperty0
fun <T> testValues(property: KMutableProperty0<T>, start: T?, vararg values: T) {
Assert.assertEquals(start, property.get())
values.forEach {
property.set(it)
Assert.assertEquals(it, property.get())
}
}
================================================
FILE: preferenceholder/src/main/AndroidManifest.xml
================================================
<manifest package="com.marcinmoskala.kotlinpreferences" />
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolder.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.marcinmoskala.kotlinpreferences.bindings.*
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
abstract class PreferenceHolder {
protected inline fun <reified T : Any> bindToPreferenceField(default: T, key: String? = null, caching: Boolean = true): ReadWriteProperty<PreferenceHolder, T>
= bindToPreferenceField(T::class, object : TypeToken<T>() {}.type, default, key, caching)
protected inline fun <reified T : Any> bindToPreferenceFieldNullable(key: String? = null, caching: Boolean = true): ReadWriteProperty<PreferenceHolder, T?>
= bindToPreferenceFieldNullable(T::class, object : TypeToken<T>() {}.type, key, caching)
protected fun <T : Any> bindToPreferenceField(clazz: KClass<T>, type: Type, default: T, key: String?, caching: Boolean = true): ReadWriteProperty<PreferenceHolder, T>
= if (caching) PreferenceFieldBinderCaching(clazz, type, default, key) else PreferenceFieldBinder(clazz, type, default, key)
protected fun <T : Any> bindToPreferenceFieldNullable(clazz: KClass<T>, type: Type, key: String?, caching: Boolean = true): ReadWriteProperty<PreferenceHolder, T?>
= if (caching) PreferenceFieldBinderNullableCaching(clazz, type, key) else PreferenceFieldBinderNullable(clazz, type, key)
/**
* Function used to clear all SharedPreference and PreferenceHolder data. Useful especially
* during tests or when implementing Logout functionality.
*/
fun clear() {
forEachDelegate { delegate, property ->
delegate.clear(this, property)
}
}
fun clearCache() {
forEachDelegate { delegate, property ->
delegate.clearCache()
}
}
private fun forEachDelegate(f: (Clearable, KProperty<*>) -> Unit) {
val pref = preferences ?: return
val properties = this::class.declaredMemberProperties
.filterIsInstance<KProperty1<SharedPreferences, *>>()
for (p in properties) {
val prevAccessible = p.isAccessible
if (!prevAccessible) p.isAccessible = true
val delegate = p.getDelegate(pref)
if (delegate is Clearable) f(delegate, p)
p.isAccessible = prevAccessible
}
}
companion object {
/**
* This property should be used to set serializer to use types that are not supported by SharedPreference.
*/
var serializer: Serializer? = null
/**
* When testing mode is turned on, then there is no need to provide Context, and all bindings
* are acting just like standard Kotln fields. If we then need to mock some situation then all
* we need to do is to set values on Preferences. Example:
*
* fun newUserCreationTest() {
* PreferenceHolder.testingMode = true
* UserPreferences.user = null
* val mockedView = object : UserView {
* fun getName() = "Marcin"
* gun getSurname() = "Moskala"
* }
* val presenter = UserPresenter(mockedView)
* presenter.createUser()
* assert(User("Marcin", "Moskala"), UserPreferences.user)
* }
*/
var testingMode: Boolean = false
/**
* It should be used to set ApplicationContext on project Application class. Only case when
* it could be ommitted is when testingMode is turned on.
*/
fun setContext(context: Context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context)
}
private const val noPreferencesSetErrorText = "No preferences in PreferenceHolder instance. Add in Application class PreferenceHolder.setContext(applicationContext) or make PreferenceHolderApplication to be your project application class (android:name field in AndroidManifest)."
internal var preferences: SharedPreferences? = null
internal fun getPreferencesOrThrowError(): SharedPreferences = PreferenceHolder.preferences ?: throw Error(noPreferencesSetErrorText)
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolderApplication.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.app.Application
class PreferenceHolderApplication : Application() {
override fun onCreate() {
super.onCreate()
PreferenceHolder.setContext(applicationContext)
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/Serializer.kt
================================================
package com.marcinmoskala.kotlinpreferences
import java.lang.reflect.Type
interface Serializer {
fun serialize(toSerialize: Any?): String?
fun deserialize(serialized: String?, type: Type): Any?
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/TypeToken.kt
================================================
package com.marcinmoskala.kotlinpreferences
import java.io.Serializable
import java.lang.reflect.GenericArrayType
import java.lang.reflect.Modifier
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.util.Arrays
open class TypeToken<T> protected constructor() {
private val superclass = javaClass.genericSuperclass as ParameterizedType
val type: Type = canonicalize(superclass.actualTypeArguments[0])
private class ParameterizedTypeImpl(ownerType: Type?, rawType: Type, vararg typeArguments: Type) : ParameterizedType, Serializable {
private val ownerType: Type?
private val rawType: Type
private val typeArguments: List<Type>
init {
// require an owner type if the raw type needs it
if (rawType is Class<*>) {
val isStaticOrTopLevelClass = Modifier.isStatic(rawType.modifiers) || rawType.enclosingClass == null
checkArgument(ownerType != null || isStaticOrTopLevelClass)
}
this.ownerType = if (ownerType == null) null else canonicalize(ownerType)
this.rawType = canonicalize(rawType)
this.typeArguments = typeArguments.map { canonicalize(it) }
}
override fun getActualTypeArguments() = typeArguments.toTypedArray()
override fun getRawType() = rawType
override fun getOwnerType() = ownerType
override fun toString(): String {
val stringBuilder = StringBuilder(30 * (typeArguments.size + 1))
stringBuilder.append(typeToString(rawType))
if (typeArguments.isEmpty()) {
return stringBuilder.toString()
}
stringBuilder.append("<").append(typeToString(typeArguments[0]))
for (i in 1 until typeArguments.size) {
stringBuilder.append(", ").append(typeToString(typeArguments[i]))
}
return stringBuilder.append(">").toString()
}
}
private class GenericArrayTypeImpl(componentType: Type) : GenericArrayType, Serializable {
private val componentType: Type = canonicalize(componentType)
override fun getGenericComponentType() = componentType
override fun toString() = typeToString(componentType) + "[]"
}
private class WildcardTypeImpl(upperBounds: Array<Type>, lowerBounds: Array<Type>) : WildcardType, Serializable {
private val upperBound: Type
private val lowerBound: Type?
init {
checkArgument(lowerBounds.size <= 1)
checkArgument(upperBounds.size == 1)
if (lowerBounds.size == 1) {
checkNotNull(lowerBounds[0])
checkNotPrimitive(lowerBounds[0])
checkArgument(upperBounds[0] === Any::class.java)
this.lowerBound = canonicalize(lowerBounds[0])
this.upperBound = Any::class.java
} else {
checkNotNull(upperBounds[0])
checkNotPrimitive(upperBounds[0])
this.lowerBound = null
this.upperBound = canonicalize(upperBounds[0])
}
}
override fun getUpperBounds() = arrayOf(upperBound)
override fun getLowerBounds() =
if (lowerBound != null) arrayOf(lowerBound) else EMPTY_TYPE_ARRAY
override fun toString(): String = when {
lowerBound != null -> "? super " + typeToString(lowerBound)
upperBound === Any::class.java -> "?"
else -> "? extends " + typeToString(upperBound)
}
}
companion object {
internal val EMPTY_TYPE_ARRAY = arrayOf<Type>()
internal fun canonicalize(type: Type): Type = if (type is Class<*>) {
if (type.isArray) GenericArrayTypeImpl(canonicalize(type.componentType)) else type
} else if (type is ParameterizedType) {
ParameterizedTypeImpl(type.ownerType, type.rawType, *type.actualTypeArguments)
} else if (type is GenericArrayType) {
GenericArrayTypeImpl(type.genericComponentType)
} else if (type is WildcardType) {
WildcardTypeImpl(type.upperBounds, type.lowerBounds)
} else {
type
}
internal fun typeToString(type: Type): String {
return if (type is Class<*>) type.name else type.toString()
}
internal fun checkNotPrimitive(type: Type) {
checkArgument(type !is Class<*> || !type.isPrimitive)
}
internal fun <T> checkNotNull(obj: T?): T = if (obj != null) obj else throw NullPointerException()
internal fun checkArgument(condition: Boolean) {
if (!condition) throw IllegalArgumentException()
}
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/Clearable.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import kotlin.reflect.KProperty
interface Clearable {
fun clear(thisRef: PreferenceHolder, property: KProperty<*>)
fun clearCache()
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/Errors.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
object Errors {
val serializerNotSet = "Serializer needs to be set if you want to use custom types"
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/GetKey.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import kotlin.reflect.KProperty
internal fun getKey(keySet: String?, property: KProperty<*>) = keySet ?: "${property.name}Key"
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinder.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import android.content.SharedPreferences
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.getPreferencesOrThrowError
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.testingMode
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
internal class PreferenceFieldBinder<T : Any>(
private val clazz: KClass<T>,
private val type: Type,
private val default: T,
private val key: String?
) : ReadWriteProperty<PreferenceHolder, T>, Clearable {
override fun clear(thisRef: PreferenceHolder, property: KProperty<*>) {
setValue(thisRef, property, default)
}
override fun clearCache() {
}
var field: T? = null
override operator fun getValue(thisRef: PreferenceHolder, property: KProperty<*>): T = when {
testingMode -> field ?: default
else -> readValue(property)
}
override fun setValue(thisRef: PreferenceHolder, property: KProperty<*>, value: T) {
if (testingMode) {
if (value == field) return
field = value
} else {
saveNewValue(property, value)
}
}
private fun saveNewValue(property: KProperty<*>, value: T) {
val pref = getPreferencesOrThrowError()
pref.edit().apply { putValue(clazz, value, getKey(key, property)) }.apply()
}
private fun readValue(property: KProperty<*>): T {
val pref = getPreferencesOrThrowError()
return pref.getValue(property)
}
private fun SharedPreferences.getValue(property: KProperty<*>): T {
val key = getKey(key, property)
return getFromPreference(clazz, type, default, key) as T
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderCaching.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import android.content.SharedPreferences
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.getPreferencesOrThrowError
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.testingMode
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
internal class PreferenceFieldBinderCaching<T : Any>(
private val clazz: KClass<T>,
private val type: Type,
private val default: T,
private val key: String?
) : ReadWriteProperty<PreferenceHolder, T>, Clearable {
override fun clear(thisRef: PreferenceHolder, property: KProperty<*>) {
setValue(thisRef, property, default)
}
override fun clearCache() {
field = null
}
var field: T? = null
override operator fun getValue(thisRef: PreferenceHolder, property: KProperty<*>): T = when {
testingMode -> field ?: default
else -> readValue(property)
}
override fun setValue(thisRef: PreferenceHolder, property: KProperty<*>, value: T) {
if (value == field) return
field = value
if (!testingMode) saveNewValue(property, value)
}
private fun saveNewValue(property: KProperty<*>, value: T) {
val pref = getPreferencesOrThrowError()
pref.edit().apply { putValue(clazz, value, getKey(key, property)) }.apply()
}
private fun readValue(property: KProperty<*>): T {
val pref = getPreferencesOrThrowError()
return pref.getValue(property)
}
private fun SharedPreferences.getValue(property: KProperty<*>): T {
val key = getKey(key, property)
return getFromPreference(clazz, type, default, key) as T
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderNullable.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.getPreferencesOrThrowError
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.testingMode
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
internal class PreferenceFieldBinderNullable<T : Any>(
private val clazz: KClass<T>,
private val type: Type,
private val key: String?
) : ReadWriteProperty<PreferenceHolder, T?>, Clearable {
override fun clear(thisRef: PreferenceHolder, property: KProperty<*>) {
setValue(thisRef, property, null)
}
override fun clearCache() {
propertySet = false
field = null
}
var propertySet: Boolean = false
var field: T? = null
override operator fun getValue(thisRef: PreferenceHolder, property: KProperty<*>): T? = when {
testingMode -> field
else -> readAndSetValue(property)
}
private fun readAndSetValue(property: KProperty<*>): T? {
val newValue = readValue(property)
field = newValue
propertySet = true
return newValue
}
override fun setValue(thisRef: PreferenceHolder, property: KProperty<*>, value: T?) {
if (testingMode) {
propertySet = true
if (value == field) return
field = value
} else {
saveNewValue(property, value)
}
}
private fun saveNewValue(property: KProperty<*>, value: T?) {
if (value == null) {
removeValue(property)
} else {
saveValue(property, value)
}
}
private fun readValue(property: KProperty<*>): T? {
val key = getKey(key, property)
val pref = getPreferencesOrThrowError()
if (!pref.contains(key)) return null
return pref.getFromPreference(clazz, type, key)
}
private fun removeValue(property: KProperty<*>) {
val pref = getPreferencesOrThrowError()
pref.edit()
.remove(getKey(key, property))
.apply()
}
private fun saveValue(property: KProperty<*>, value: T) {
val pref = getPreferencesOrThrowError()
pref.edit().apply { putValue(clazz, value, getKey(key, property)) }.apply()
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderNullableCaching.kt
================================================
package com.marcinmoskala.kotlinpreferences.bindings
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.getPreferencesOrThrowError
import com.marcinmoskala.kotlinpreferences.PreferenceHolder.Companion.testingMode
import java.lang.reflect.Type
import kotlin.concurrent.thread
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
internal class PreferenceFieldBinderNullableCaching<T : Any>(
private val clazz: KClass<T>,
private val type: Type,
private val key: String?
) : ReadWriteProperty<PreferenceHolder, T?>, Clearable {
override fun clear(thisRef: PreferenceHolder, property: KProperty<*>) {
setValue(thisRef, property, null)
}
override fun clearCache() {
propertySet = false
field = null
}
var propertySet: Boolean = false
var field: T? = null
override operator fun getValue(thisRef: PreferenceHolder, property: KProperty<*>): T? = when {
testingMode || propertySet -> field
else -> readAndSetValue(property)
}
private fun readAndSetValue(property: KProperty<*>): T? {
val newValue = readValue(property)
field = newValue
propertySet = true
return newValue
}
override fun setValue(thisRef: PreferenceHolder, property: KProperty<*>, value: T?) {
propertySet = true
if (value == field) return
field = value
if (!testingMode)
saveNewValue(property, value)
}
private fun saveNewValue(property: KProperty<*>, value: T?) {
thread {
if (value == null) {
removeValue(property)
} else {
saveValue(property, value)
}
}
}
private fun readValue(property: KProperty<*>): T? {
val key = getKey(key, property)
val pref = getPreferencesOrThrowError()
if (!pref.contains(key)) return null
return pref.getFromPreference(clazz, type, key)
}
private fun removeValue(property: KProperty<*>) {
val pref = getPreferencesOrThrowError()
pref.edit()
.remove(getKey(key, property))
.apply()
}
private fun saveValue(property: KProperty<*>, value: T) {
val pref = getPreferencesOrThrowError()
pref.edit().apply { putValue(clazz, value, getKey(key, property)) }.apply()
}
}
================================================
FILE: preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PutValueExt.kt
================================================
@file:Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
package com.marcinmoskala.kotlinpreferences.bindings
import android.content.SharedPreferences
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import java.lang.reflect.Type
import kotlin.reflect.KClass
internal fun SharedPreferences.Editor.putValue(clazz: KClass<*>, value: Any, key: String) {
when (clazz.simpleName) {
"Long" -> putLong(key, value as Long)
"Int" -> putInt(key, value as Int)
"String" -> putString(key, value as String?)
"Boolean" -> putBoolean(key, value as Boolean)
"Float" -> putFloat(key, value as Float)
else -> putString(key, value.serialize())
}
}
internal fun <T : Any> SharedPreferences.getFromPreference(clazz: KClass<T>, type: Type, default: T?, key: String): T? = when (clazz.simpleName) {
"Long" -> getLong(key, default as Long) as? T
"Int" -> getInt(key, default as Int) as? T
"String" -> getString(key, default as? String) as? T
"Boolean" -> getBoolean(key, default as Boolean) as? T
"Float" -> getFloat(key, default as Float) as? T
else -> getString(key, default.serialize()).deserialize(type)
}
internal fun <T: Any> SharedPreferences.getFromPreference(clazz: KClass<T>, type: Type, key: String): T?
= getFromPreference(clazz, type, getDefault(clazz), key)
private fun <T: Any> String.deserialize(type: Type): T? = getSerializer().deserialize(this, type) as? T
private fun <T> T.serialize() = getSerializer().serialize(this)
private fun getSerializer() = PreferenceHolder.serializer ?: throw Error(Errors.serializerNotSet)
private fun <T: Any> getDefault(clazz: KClass<T>): T? = when(clazz.simpleName) {
"Long" -> -1L
"Int" -> -1
"Boolean" -> false
"Float" -> -1.0F
else -> null
} as? T
================================================
FILE: preferenceholder-gson-serializer/.gitignore
================================================
/build
================================================
FILE: preferenceholder-gson-serializer/build.gradle
================================================
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'com.github.dcendents.android-maven'
group='com.marcinmoskala'
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
minSdkVersion 14
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
compile project(':preferenceholder')
compile "com.google.code.gson:gson:2.8.0"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
// Fancy test print
tasks.withType(Test) {
testLogging {
// set options for log level LIFECYCLE
events "passed", "skipped", "failed", "standardOut"
showExceptions true
exceptionFormat "full"
showCauses true
showStackTraces true
// set options for log level DEBUG and INFO
debug {
events "started", "passed", "skipped", "failed", "standardOut", "standardError"
exceptionFormat "full"
}
info.events = debug.events
info.exceptionFormat = debug.exceptionFormat
afterSuite { desc, result ->
if (!desc.parent) { // will match the outermost suite
def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
def startItem = '| ', endItem = ' |'
def repeatLength = startItem.length() + output.length() + endItem.length()
println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
}
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
install {
repositories.mavenInstaller {
pom.project {
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
}
}
}
================================================
FILE: preferenceholder-gson-serializer/proguard-rules.pro
================================================
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/DeserializationTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.runner.AndroidJUnit4
import com.google.gson.Gson
import com.marcinmoskala.kotlinpreferences.gson.GsonSerializer
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DeserializationTest : GsonBaseTest() {
data class User(var name: String, var age: Int = 0)
@Test
fun listDeserializationTest() {
val json = "[{\"age\"=\"0\", \"name\"=\"Name0\"}, {\"age\"=\"1\", \"name\"=\"Name1\"}, {\"age\"=\"2\", \"name\"=\"Name2\"}]"
val users = GsonSerializer(Gson()).deserialize(json, object : TypeToken<List<User>>() {}.type)
val expected = List(3) { i -> User("Name$i", i) }
Assert.assertEquals(expected, users)
}
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/GsonBaseTest.kt
================================================
package com.marcinmoskala.kotlinpreferences
import android.support.test.InstrumentationRegistry
import com.google.gson.Gson
import com.marcinmoskala.kotlinpreferences.collections.CollectionsPref
import com.marcinmoskala.kotlinpreferences.gson.GsonSerializer
import com.marcinmoskala.kotlinpreferences.objects.ComplexTestPreferences
open class GsonBaseTest {
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
PreferenceHolder.serializer = GsonSerializer(Gson())
ComplexTestPreferences.clear()
CollectionsPref.clear()
}
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/TestUtills.kt
================================================
package com.marcinmoskala.kotlinpreferences
import org.junit.Assert
import kotlin.reflect.KMutableProperty0
fun <T> testValues(property: KMutableProperty0<T>, start: T?, vararg values: T) {
Assert.assertEquals(start, property.get())
values.forEach {
property.set(it)
Assert.assertEquals(it, property.get())
}
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/collections/CollectionsConfig.kt
================================================
package com.marcinmoskala.kotlinpreferences.collections
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.objects.Character
object CollectionsPref: PreferenceHolder() {
var intList: List<Int>? by bindToPreferenceFieldNullable()
var stringList: List<String> by bindToPreferenceField(listOf())
var longList: Map<Int, Long> by bindToPreferenceField(mapOf(0 to 12L, 10 to 143L))
var propTest: List<Character>? by bindToPreferenceFieldNullable()
var elemTest: Set<Elems> by bindToPreferenceField(setOf(Elems.Elem1, Elems.Elem3))
var multiLevelList: List<List<Int>>? by bindToPreferenceFieldNullable()
}
enum class Elems {
Elem1,
Elem2,
Elem3,
Elem4,
Elem5
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/collections/CollectionsTest.kt
================================================
package com.marcinmoskala.kotlinpreferences.collections
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.GsonBaseTest
import com.marcinmoskala.kotlinpreferences.collections.Elems.*
import com.marcinmoskala.kotlinpreferences.objects.Character
import com.marcinmoskala.kotlinpreferences.testValues
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PreferenceFieldNullableTest : GsonBaseTest() {
@Test
fun intListTest() {
testValues(CollectionsPref::intList, null, listOf(1, 2, 3, 4), listOf(4, 3, 2, 1), listOf())
}
@Test
fun stringListTest() {
testValues(CollectionsPref::stringList, listOf(), listOf("Test1", "Test2", "Test3"), listOf(), listOf("Test3"), listOf("Test1", "Test2"))
}
@Test
fun longMapTest() {
testValues(CollectionsPref::longList, mapOf(0 to 12L, 10 to 143L), mapOf(100 to 1000L), mapOf(), mapOf(0 to 1L, 1 to 2L, 2 to 3L))
}
@Test
fun complexListTest() {
val character1 = Character("Marcin", "Human", "Wizzard")
val character2 = Character("SuperMarcin", "SuperHuman", "SuperWizzard")
testValues(CollectionsPref::propTest, null, listOf(character1), listOf(character1, character2), listOf(character1))
}
@Test
fun enumSetChangeTest() {
testValues(CollectionsPref::elemTest, setOf(Elem1, Elem3), setOf(), setOf(Elem4, Elem3), setOf(Elem1, Elem2, Elem3, Elem4, Elem5), setOf())
}
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/issue2test/Issue2Test.kt
================================================
package com.marcinmoskala.kotlinpreferences.issue2test
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.kotlinpreferences.gson.GsonSerializer
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class Issue2Test {
data class User(var name: String, var age: Int = 0)
object AppPreference : PreferenceHolder() {
var users: List<User>? by bindToPreferenceFieldNullable()
}
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
PreferenceHolder.serializer = GsonSerializer(Gson())
}
@Test
fun booleanDefaultChangeTest() {
val users = List(6) { i -> User("Name$i", i) }
AppPreference.users = users
AppPreference.clearCache()
val readUsers = AppPreference.users
Assert.assertEquals(users, readUsers)
}
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/objects/ObjectConfig.kt
================================================
package com.marcinmoskala.kotlinpreferences.objects
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
object ComplexTestPreferences: PreferenceHolder() {
var character: Character? by bindToPreferenceFieldNullable()
var savedGame: Game? by bindToPreferenceFieldNullable()
}
data class Character(
val name: String,
val race: String,
val clazz: String
)
data class Game(
val character: Character,
val gameMode: GameMode,
val level: Int
)
enum class GameMode {
Easy, Normal, Hard
}
================================================
FILE: preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/objects/ObjectsTest.kt
================================================
package com.marcinmoskala.kotlinpreferences.objects
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.GsonBaseTest
import com.marcinmoskala.kotlinpreferences.testValues
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ObjectsTest: GsonBaseTest() {
@Test
fun characterTest() {
val character1 = Character("Marcin", "Human", "Wizzard")
val character2 = Character("Marcin", "SuperHuman", "Wizzard")
testValues(ComplexTestPreferences::character, null, character1, character2)
}
@Test
fun bigObjectTest() {
val game1 = Game(Character("Marcin", "Human", "Wizzard"), GameMode.Hard, 100)
testValues(ComplexTestPreferences::savedGame, null, game1)
}
}
================================================
FILE: preferenceholder-gson-serializer/src/main/AndroidManifest.xml
================================================
<manifest package="com.marcinmoskala.kotlinpreferences.gson" />
================================================
FILE: preferenceholder-gson-serializer/src/main/java/com/marcinmoskala/kotlinpreferences/gson/GsonSerializer.kt
================================================
package com.marcinmoskala.kotlinpreferences.gson
import com.google.gson.Gson
import com.marcinmoskala.kotlinpreferences.Serializer
import java.lang.reflect.Type
class GsonSerializer(val gson: Gson) : Serializer {
override fun serialize(toSerialize: Any?): String? = gson.toJson(toSerialize)
override fun deserialize(serialized: String?, type: Type): Any? = try {
gson.fromJson<Any>(serialized, type)
} catch (e: Throwable) {
throw Error("Error in parsing to $type. The string to parse: \"$this\"", e)
}
}
================================================
FILE: sample/.gitignore
================================================
/build
================================================
FILE: sample/build.gradle
================================================
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.marcinmoskala.testapp"
minSdkVersion 14
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile project(':preferenceholder')
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.android.support:appcompat-v7:27.0.1'
testCompile 'junit:junit:4.12'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
================================================
FILE: sample/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/marcin/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: sample/src/androidTest/java/com/marcinmoskala/testapp/DefaultChangeTest.kt
================================================
package com.marcinmoskala.testapp
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.testapp.TestPreferences.canEatPie
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.reflect.KMutableProperty0
@RunWith(AndroidJUnit4::class)
class DefaultChangeTest {
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
TestPreferences.clear()
}
@Test
fun booleanDefaultChangeTest() {
testBoolean(TestPreferences::canEatPie)
}
private fun testBoolean(property: KMutableProperty0<Boolean>) {
assertTrue(property.get())
property.set(false)
canEatPie = false
assertTrue(!canEatPie)
canEatPie = true
assertTrue(canEatPie)
}
@Test
fun intDefaultChangeTest() {
assertEquals(0, TestPreferences.pieBaked)
TestPreferences.pieBaked = 10
assertEquals(10, TestPreferences.pieBaked)
TestPreferences.pieBaked += 10
assertEquals(20, TestPreferences.pieBaked)
}
@Test
fun longDefaultChangeTest() {
assertEquals(0L, TestPreferences.allPieInTheWorld)
TestPreferences.allPieInTheWorld = 10
assertEquals(10L, TestPreferences.allPieInTheWorld)
TestPreferences.allPieInTheWorld += 10
assertEquals(20L, TestPreferences.allPieInTheWorld)
}
@Test
fun floatDefaultChangeTest() {
assertEquals(0F, TestPreferences.pieEaten)
for (i in 1..10) TestPreferences.pieEaten += 1F
assertEquals(10F, TestPreferences.pieEaten)
TestPreferences.pieEaten *= 2
assertEquals(20F, TestPreferences.pieEaten)
}
@Test
fun stringDefaultChangeTest() {
assertEquals("Pie", TestPreferences.bestPieName)
TestPreferences.bestPieName = "BlueberryPie"
assertEquals("BlueberryPie", TestPreferences.bestPieName)
TestPreferences.bestPieName = "SuperPie"
assertEquals("SuperPie", TestPreferences.bestPieName)
}
}
================================================
FILE: sample/src/androidTest/java/com/marcinmoskala/testapp/ExampleConfig.kt
================================================
package com.marcinmoskala.testapp
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
object TestPreferences: PreferenceHolder() {
var canEatPie: Boolean by bindToPreferenceField(true)
var pieBaked: Int by bindToPreferenceField(0)
var allPieInTheWorld: Long by bindToPreferenceField(0)
var pieEaten: Float by bindToPreferenceField(0.0F)
var bestPieName: String by bindToPreferenceField("Pie")
var isMonsterKiller: Boolean? by bindToPreferenceFieldNullable()
var monstersKilled: Int? by bindToPreferenceFieldNullable()
var numberOfHahaInLough: Long? by bindToPreferenceFieldNullable()
var experience: Float? by bindToPreferenceFieldNullable()
var className: String? by bindToPreferenceFieldNullable()
}
object ComplexTestPreferences: PreferenceHolder() {
var character: Character? by bindToPreferenceFieldNullable()
var savedGame: Game? by bindToPreferenceFieldNullable()
}
data class Character(
val name: String,
val race: String,
val clazz: String
)
class Game(
val character: Character,
val gameMode: GameMode,
val level: Int
)
enum class GameMode {
Easy, Normal, Hard
}
================================================
FILE: sample/src/androidTest/java/com/marcinmoskala/testapp/NullableChangeTest.kt
================================================
package com.marcinmoskala.testapp
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.testapp.TestPreferences.className
import com.marcinmoskala.testapp.TestPreferences.experience
import com.marcinmoskala.testapp.TestPreferences.isMonsterKiller
import com.marcinmoskala.testapp.TestPreferences.monstersKilled
import com.marcinmoskala.testapp.TestPreferences.numberOfHahaInLough
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class NullableChangeTest {
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
TestPreferences.clear()
}
@Test
fun booleanDefaultChangeTest() {
assertNull(isMonsterKiller)
isMonsterKiller = true
assertTrue(isMonsterKiller!!)
isMonsterKiller = false
assertTrue(!isMonsterKiller!!)
isMonsterKiller = null
assertNull(isMonsterKiller)
}
@Test
fun intDefaultChangeTest() {
assertNull(monstersKilled)
monstersKilled = 1
assertEquals(1, monstersKilled!!)
monstersKilled = monstersKilled?.plus(1)
assertEquals(2, monstersKilled!!)
monstersKilled = null
assertNull(monstersKilled)
}
@Test
fun longDefaultChangeTest() {
assertNull(numberOfHahaInLough)
numberOfHahaInLough = 10
assertEquals(10, numberOfHahaInLough!!)
numberOfHahaInLough = 100
assertEquals(100, numberOfHahaInLough!!)
numberOfHahaInLough = null
assertNull(numberOfHahaInLough)
}
@Test
fun floatDefaultChangeTest() {
assertNull(experience)
experience = 0.0F
assertEquals(0.0F, experience!!)
experience = 10.0F
assertEquals(10.0F, experience!!)
experience = null
assertNull(experience)
}
@Test
fun stringDefaultChangeTest() {
assertNull(className)
className = "Rouge"
assertEquals("Rouge", className!!)
className = "Wizard"
assertEquals("Wizard", className!!)
className = null
assertNull(className)
}
}
================================================
FILE: sample/src/androidTest/java/com/marcinmoskala/testapp/NullableClassesChangeTest.kt
================================================
package com.marcinmoskala.testapp
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
import com.marcinmoskala.testapp.ComplexTestPreferences.character
import com.marcinmoskala.testapp.ComplexTestPreferences.savedGame
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class NullableClassesChangeTest {
init {
PreferenceHolder.setContext(InstrumentationRegistry.getTargetContext())
ComplexTestPreferences.clear()
}
@Test
fun characterTest() {
assertNull(character)
character = Character("Marcin", "Human", "Wizzard")
assertEquals(Character("Marcin", "Human", "Wizzard"), character!!)
character = character!!.copy(race = "SuperHuman")
assertEquals("SuperHuman", character!!.race)
assertEquals(Character("Marcin", "SuperHuman", "Wizzard"), character!!)
}
@Test
fun bigObjectTest() {
assertNull(savedGame)
savedGame = Game(Character("Marcin", "Human", "Wizzard"), GameMode.Hard, 100)
assertEquals(Character("Marcin", "Human", "Wizzard"), savedGame!!.character)
assertEquals(GameMode.Hard, savedGame!!.gameMode)
assertEquals(100, savedGame!!.level)
}
}
================================================
FILE: sample/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marcinmoskala.testapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name="com.marcinmoskala.kotlinpreferences.PreferenceHolderApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
================================================
FILE: sample/src/main/java/com/marcinmoskala/testapp/MainActivity.kt
================================================
package com.marcinmoskala.testapp
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val text: String
get() = textEditView.text.toString()
val num: Int
get() = numberEditView.text.toString().toInt()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textEditView.setText(Pref.text)
numberEditView.setText(Pref.num.toString())
textEditView.setOnKeyListener { v, k, e -> Pref.text = text; true }
numberEditView.setOnKeyListener { v, k, e -> Pref.num = num; true }
saveObjectButton.setOnClickListener {
val newObject = OtherPref.Together(text, num)
OtherPref.together = newObject
objectMonitor.text = newObject.toString()
}
}
}
================================================
FILE: sample/src/main/java/com/marcinmoskala/testapp/Pref.kt
================================================
package com.marcinmoskala.testapp
import com.marcinmoskala.kotlinpreferences.PreferenceHolder
object Pref : PreferenceHolder() {
var text: String? by bindToPreferenceFieldNullable()
var num: Int by bindToPreferenceField(0, "SomeIntKey")
}
object OtherPref : PreferenceHolder() {
var together: Together? by bindToPreferenceFieldNullable("SomeOtherKey")
data class Together(
val text: String,
val num: Int?
)
}
================================================
FILE: sample/src/main/res/layout/activity_main.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.marcinmoskala.testapp.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/textEditView"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_margin="10dp"
android:textColor="@color/colorPrimary"
android:ems="10"
android:inputType="textPersonName"/>
<EditText
android:id="@+id/numberEditView"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_margin="10dp"
android:textColor="@color/colorPrimary"
android:ems="10"
android:inputType="number"/>
<Button
android:id="@+id/saveObjectButton"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_margin="10dp"
android:ems="10"
android:text="Save object"/>
<TextView
android:id="@+id/objectMonitor"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_margin="10dp"
android:ems="10"
android:textColor="@color/colorPrimary"
android:inputType="textPersonName"
android:text="Name"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="13dp" />
</LinearLayout>
</ScrollView>
================================================
FILE: sample/src/main/res/values/colors.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
================================================
FILE: sample/src/main/res/values/strings.xml
================================================
<resources>
<string name="app_name">TestApp</string>
</resources>
================================================
FILE: sample/src/main/res/values/styles.xml
================================================
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
================================================
FILE: settings.gradle
================================================
include ':preferenceholder', ':preferenceholder-gson-serializer', ':sample'
gitextract_ryqsddrd/ ├── .codebeatignore ├── .gitignore ├── .travis.yml ├── LICENSE ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── preferenceholder/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── marcinmoskala/ │ │ └── kotlinpreferences/ │ │ ├── BaseTest.kt │ │ ├── CleaningTest.kt │ │ ├── ExampleConfig.kt │ │ ├── PreferenceFieldNullableTest.kt │ │ ├── PreferenceFieldTest.kt │ │ └── TestUtills.kt │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── marcinmoskala/ │ └── kotlinpreferences/ │ ├── PreferenceHolder.kt │ ├── PreferenceHolderApplication.kt │ ├── Serializer.kt │ ├── TypeToken.kt │ └── bindings/ │ ├── Clearable.kt │ ├── Errors.kt │ ├── GetKey.kt │ ├── PreferenceFieldBinder.kt │ ├── PreferenceFieldBinderCaching.kt │ ├── PreferenceFieldBinderNullable.kt │ ├── PreferenceFieldBinderNullableCaching.kt │ └── PutValueExt.kt ├── preferenceholder-gson-serializer/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── marcinmoskala/ │ │ └── kotlinpreferences/ │ │ ├── DeserializationTest.kt │ │ ├── GsonBaseTest.kt │ │ ├── TestUtills.kt │ │ ├── collections/ │ │ │ ├── CollectionsConfig.kt │ │ │ └── CollectionsTest.kt │ │ ├── issue2test/ │ │ │ └── Issue2Test.kt │ │ └── objects/ │ │ ├── ObjectConfig.kt │ │ └── ObjectsTest.kt │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── marcinmoskala/ │ └── kotlinpreferences/ │ └── gson/ │ └── GsonSerializer.kt ├── sample/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── marcinmoskala/ │ │ └── testapp/ │ │ ├── DefaultChangeTest.kt │ │ ├── ExampleConfig.kt │ │ ├── NullableChangeTest.kt │ │ └── NullableClassesChangeTest.kt │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── marcinmoskala/ │ │ └── testapp/ │ │ ├── MainActivity.kt │ │ └── Pref.kt │ └── res/ │ ├── layout/ │ │ └── activity_main.xml │ └── values/ │ ├── colors.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle
Condensed preview — 62 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (100K chars).
[
{
"path": ".codebeatignore",
"chars": 242,
"preview": "preferenceholder-lib/src/androidTest/**\npreferenceholder-lib/src/main/java/com/marcinmoskala/kotlinpreferences/Preferenc"
},
{
"path": ".gitignore",
"chars": 89,
"preview": "*.iml\n.gradle\n/local.properties\n/.idea/*\n.DS_Store\n/build\n/captures\n.externalNativeBuild\n"
},
{
"path": ".travis.yml",
"chars": 753,
"preview": "language: android\njdk: oraclejdk8\n\nandroid:\n components:\n - tools\n - platform-tools\n - build-tools-27.0.1\n "
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "LICENSE.txt",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 6167,
"preview": "# PreferenceHolder\nKotlin Android Library, that makes preference usage simple and fun.\n\n[\n jcenter()\n maven"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 230,
"preview": "#Tue Nov 28 16:54:24 CET 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
},
{
"path": "gradle.properties",
"chars": 730,
"preview": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will o"
},
{
"path": "gradlew",
"chars": 4971,
"preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n## Gradle start "
},
{
"path": "gradlew.bat",
"chars": 2314,
"preview": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem "
},
{
"path": "preferenceholder/.gitignore",
"chars": 7,
"preview": "/build\n"
},
{
"path": "preferenceholder/build.gradle",
"chars": 2418,
"preview": "apply plugin: 'com.android.library'\napply plugin: 'kotlin-android'\n\napply plugin: 'com.github.dcendents.android-maven'\n\n"
},
{
"path": "preferenceholder/proguard-rules.pro",
"chars": 0,
"preview": ""
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/BaseTest.kt",
"chars": 294,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.InstrumentationRegistry\n\nopen class BaseTest {\n"
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/CleaningTest.kt",
"chars": 2041,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.runner.AndroidJUnit4\nimport com.marcinmoskala.k"
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/ExampleConfig.kt",
"chars": 703,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nobject TestPreferences: PreferenceHolder() {\n var canEatPie: Boolean by "
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/PreferenceFieldNullableTest.kt",
"chars": 1243,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.runner.AndroidJUnit4\nimport com.marcinmoskala.k"
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/PreferenceFieldTest.kt",
"chars": 848,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.runner.AndroidJUnit4\nimport org.junit.Test\nimpo"
},
{
"path": "preferenceholder/src/androidTest/java/com/marcinmoskala/kotlinpreferences/TestUtills.kt",
"chars": 340,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport org.junit.Assert\nimport kotlin.reflect.KMutableProperty0\n\nfun <T> te"
},
{
"path": "preferenceholder/src/main/AndroidManifest.xml",
"chars": 58,
"preview": "<manifest package=\"com.marcinmoskala.kotlinpreferences\" />"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolder.kt",
"chars": 4485,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.content.Context\nimport android.content.SharedPreferences\nimp"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/PreferenceHolderApplication.kt",
"chars": 247,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.app.Application\n\nclass PreferenceHolderApplication : Applica"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/Serializer.kt",
"chars": 208,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport java.lang.reflect.Type\n\ninterface Serializer {\n\n fun serialize(to"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/TypeToken.kt",
"chars": 4805,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport java.io.Serializable\nimport java.lang.reflect.GenericArrayType\nimpor"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/Clearable.kt",
"chars": 256,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\nimport"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/Errors.kt",
"chars": 159,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nobject Errors {\n val serializerNotSet = \"Serializer needs to be"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/GetKey.kt",
"chars": 182,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport kotlin.reflect.KProperty\n\ninternal fun getKey(keySet: Strin"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinder.kt",
"chars": 1876,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport android.content.SharedPreferences\nimport com.marcinmoskala."
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderCaching.kt",
"chars": 1856,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport android.content.SharedPreferences\nimport com.marcinmoskala."
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderNullable.kt",
"chars": 2430,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\nimport"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PreferenceFieldBinderNullableCaching.kt",
"chars": 2492,
"preview": "package com.marcinmoskala.kotlinpreferences.bindings\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\nimport"
},
{
"path": "preferenceholder/src/main/java/com/marcinmoskala/kotlinpreferences/bindings/PutValueExt.kt",
"chars": 1805,
"preview": "@file:Suppress(\"UNCHECKED_CAST\", \"IMPLICIT_CAST_TO_ANY\")\n\npackage com.marcinmoskala.kotlinpreferences.bindings\n\nimport a"
},
{
"path": "preferenceholder-gson-serializer/.gitignore",
"chars": 7,
"preview": "/build\n"
},
{
"path": "preferenceholder-gson-serializer/build.gradle",
"chars": 2511,
"preview": "apply plugin: 'com.android.library'\napply plugin: 'kotlin-android'\n\napply plugin: 'com.github.dcendents.android-maven'\n\n"
},
{
"path": "preferenceholder-gson-serializer/proguard-rules.pro",
"chars": 0,
"preview": ""
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/DeserializationTest.kt",
"chars": 791,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.runner.AndroidJUnit4\nimport com.google.gson.Gso"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/GsonBaseTest.kt",
"chars": 591,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport android.support.test.InstrumentationRegistry\nimport com.google.gson."
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/TestUtills.kt",
"chars": 340,
"preview": "package com.marcinmoskala.kotlinpreferences\n\nimport org.junit.Assert\nimport kotlin.reflect.KMutableProperty0\n\nfun <T> te"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/collections/CollectionsConfig.kt",
"chars": 755,
"preview": "package com.marcinmoskala.kotlinpreferences.collections\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\nimp"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/collections/CollectionsTest.kt",
"chars": 1502,
"preview": "package com.marcinmoskala.kotlinpreferences.collections\n\nimport android.support.test.runner.AndroidJUnit4\nimport com.mar"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/issue2test/Issue2Test.kt",
"chars": 1111,
"preview": "package com.marcinmoskala.kotlinpreferences.issue2test\n\nimport android.support.test.InstrumentationRegistry\nimport andro"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/objects/ObjectConfig.kt",
"chars": 552,
"preview": "package com.marcinmoskala.kotlinpreferences.objects\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\n\nobject"
},
{
"path": "preferenceholder-gson-serializer/src/androidTest/java/com/marcinmoskala/kotlinpreferences/objects/ObjectsTest.kt",
"chars": 793,
"preview": "package com.marcinmoskala.kotlinpreferences.objects\n\nimport android.support.test.runner.AndroidJUnit4\nimport com.marcinm"
},
{
"path": "preferenceholder-gson-serializer/src/main/AndroidManifest.xml",
"chars": 63,
"preview": "<manifest package=\"com.marcinmoskala.kotlinpreferences.gson\" />"
},
{
"path": "preferenceholder-gson-serializer/src/main/java/com/marcinmoskala/kotlinpreferences/gson/GsonSerializer.kt",
"chars": 540,
"preview": "package com.marcinmoskala.kotlinpreferences.gson\n\nimport com.google.gson.Gson\nimport com.marcinmoskala.kotlinpreferences"
},
{
"path": "sample/.gitignore",
"chars": 7,
"preview": "/build\n"
},
{
"path": "sample/build.gradle",
"chars": 1000,
"preview": "apply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply plugin: 'kotlin-android-extensions'\n\nandroi"
},
{
"path": "sample/proguard-rules.pro",
"chars": 935,
"preview": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /U"
},
{
"path": "sample/src/androidTest/java/com/marcinmoskala/testapp/DefaultChangeTest.kt",
"chars": 2206,
"preview": "package com.marcinmoskala.testapp\n\nimport android.support.test.InstrumentationRegistry\nimport android.support.test.runne"
},
{
"path": "sample/src/androidTest/java/com/marcinmoskala/testapp/ExampleConfig.kt",
"chars": 1188,
"preview": "package com.marcinmoskala.testapp\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\n\nobject TestPreferences: "
},
{
"path": "sample/src/androidTest/java/com/marcinmoskala/testapp/NullableChangeTest.kt",
"chars": 2281,
"preview": "package com.marcinmoskala.testapp\n\nimport android.support.test.InstrumentationRegistry\nimport android.support.test.runne"
},
{
"path": "sample/src/androidTest/java/com/marcinmoskala/testapp/NullableClassesChangeTest.kt",
"chars": 1405,
"preview": "package com.marcinmoskala.testapp\n\nimport android.support.test.InstrumentationRegistry\nimport android.support.test.runne"
},
{
"path": "sample/src/main/AndroidManifest.xml",
"chars": 805,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package="
},
{
"path": "sample/src/main/java/com/marcinmoskala/testapp/MainActivity.kt",
"chars": 958,
"preview": "package com.marcinmoskala.testapp\n\nimport android.os.Bundle\nimport android.support.v7.app.AppCompatActivity\nimport kotli"
},
{
"path": "sample/src/main/java/com/marcinmoskala/testapp/Pref.kt",
"chars": 456,
"preview": "package com.marcinmoskala.testapp\n\nimport com.marcinmoskala.kotlinpreferences.PreferenceHolder\n\nobject Pref : Preference"
},
{
"path": "sample/src/main/res/layout/activity_main.xml",
"chars": 1945,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:"
},
{
"path": "sample/src/main/res/values/colors.xml",
"chars": 208,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <color name=\"colorPrimary\">#3F51B5</color>\n <color name=\"color"
},
{
"path": "sample/src/main/res/values/strings.xml",
"chars": 70,
"preview": "<resources>\n <string name=\"app_name\">TestApp</string>\n</resources>\n"
},
{
"path": "sample/src/main/res/values/styles.xml",
"chars": 363,
"preview": "<resources>\n\n <!-- Base application theme. -->\n <style name=\"AppTheme\" parent=\"Theme.AppCompat\">\n <!-- Cust"
},
{
"path": "settings.gradle",
"chars": 76,
"preview": "include ':preferenceholder', ':preferenceholder-gson-serializer', ':sample'\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the MarcinMoskala/PreferenceHolder GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 62 files (88.9 KB), approximately 23.5k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.