├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── pixplicity │ │ └── easyprefs │ │ └── library │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── pixplicity │ │ └── easyprefs │ │ └── library │ │ └── Prefs.java │ └── res │ └── values │ └── about_easypreferences_strings.xml ├── license.txt ├── mavencentral_publish.gradle ├── sample ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── pixplicity │ │ └── easyprefs │ │ └── sample │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── pixplicity │ │ └── easyprefs │ │ └── sample │ │ ├── MainActivity.java │ │ └── PrefsApplication.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | #Android generated 2 | bin 3 | gen 4 | 5 | #Eclipse 6 | .project 7 | .classpath 8 | .settings 9 | 10 | #IntelliJ IDEA 11 | .idea 12 | *.iml 13 | *.ipr 14 | *.iws 15 | out 16 | 17 | #Maven 18 | target 19 | release.properties 20 | pom.xml.* 21 | 22 | #Ant 23 | build.xml 24 | local.properties 25 | proguard.cfg 26 | 27 | #Gradle 28 | .gradle 29 | build 30 | 31 | #OSX 32 | .DS_Store 33 | 34 | #Personal Files 35 | signing.properties 36 | .signing/ 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | jdk: oraclejdk8 4 | 5 | sudo: false 6 | 7 | branches: 8 | only: 9 | - master 10 | 11 | android: 12 | components: 13 | # Uncomment the lines below if you want to 14 | # use the latest revision of Android SDK Tools 15 | # - platform-tools 16 | # - tools 17 | 18 | # The BuildTools version used by your project 19 | - build-tools-22.0.1 20 | 21 | # The SDK version used to compile your project 22 | - android-22 23 | 24 | # Additional components 25 | - extra-google-google_play_services 26 | - extra-google-m2repository 27 | - extra-android-m2repository 28 | - addon-google_apis-google-21 29 | 30 | script: 31 | - TERM=dumb ./gradlew clean assemble -PdisablePreDex 32 | 33 | notifications: 34 | email: false 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | EasyPrefs 2 | === 3 | 4 | **Deprecation notice:** Since the arrival of Kotlin it has become easy to use the preferences in a typesafe manner without much boilerplate, for example, using [this method](https://medium.com/swlh/sharedpreferences-in-android-using-kotlin-6d3bb4ffb71c). We advice to skip EasyPrefs for your next project. 5 | 6 | --- 7 | 8 | A small library containing a wrapper/helper for the shared preferences of Android. 9 | 10 | With this library you can initialize the shared preference inside the onCreate of the Application class of your app. 11 | 12 | Java: 13 | 14 | ```Java 15 | public class PrefsApplication extends Application { 16 | 17 | @Override 18 | public void onCreate() { 19 | super.onCreate(); 20 | // Initialize the Prefs class 21 | new Prefs.Builder() 22 | .setContext(this) 23 | .setMode(ContextWrapper.MODE_PRIVATE) 24 | .setPrefsName(getPackageName()) 25 | .setUseDefaultSharedPreference(true) 26 | .build(); 27 | } 28 | } 29 | ``` 30 | 31 | Kotlin: 32 | 33 | ```Kotlin 34 | class PrefsApplication : Application() { 35 | 36 | override fun onCreate() { 37 | super.onCreate() 38 | // Initialize the Prefs class 39 | Prefs.Builder() 40 | .setContext(this) 41 | .setMode(ContextWrapper.MODE_PRIVATE) 42 | .setPrefsName(packageName) 43 | .setUseDefaultSharedPreference(true) 44 | .build() 45 | } 46 | 47 | } 48 | ``` 49 | 50 | # Usage 51 | 52 | After initialization, you can use simple one-line methods to save values to the shared preferences anywhere in your app, such as: 53 | 54 | - `Prefs.putString(key, string)` 55 | - `Prefs.putLong(key, long)` 56 | - `Prefs.putBoolean(key, boolean)` 57 | 58 | Retrieving data from the Shared Preferences can be as simple as: 59 | 60 | String data = Prefs.getString(key, default value) 61 | 62 | If the shared preferences contains the key, the string will be obtained, otherwise the method returns the default string provided. No need for those pesky `contains()` or `data != null` checks! 63 | 64 | For some examples, see the sample App. 65 | 66 | ## Bonus feature: ordered sets 67 | 68 | The default implementation of `getStringSet` on Android **does not preserve the order of the strings in the set**. For this purpose, EasyPrefs adds the methods: 69 | 70 | void Prefs.putOrderedStringSet(String key, Set value); 71 | 72 | and 73 | 74 | Set Prefs.getOrderedStringSet(String key, Set defaultValue); 75 | 76 | which internally use Java's LinkedHashSet to retain a predictable iteration order. These methods have the added benefit of adding the missing functionality of storing sets to pre-Honeycomb devices. 77 | 78 | 79 | # Download 80 | 81 | Grab the latest dependency through Gradle: 82 | 83 | ```Groovy 84 | dependencies { 85 | implementation 'com.pixplicity.easyprefs:EasyPrefs:1.10.0' 86 | } 87 | ``` 88 | 89 | 90 | # License 91 | 92 | ``` 93 | Copyright 2014 Pixplicity (http://pixplicity.com) 94 | 95 | Licensed under the Apache License, Version 2.0 (the "License"); 96 | you may not use this file except in compliance with the License. 97 | You may obtain a copy of the License at 98 | 99 | http://www.apache.org/licenses/LICENSE-2.0 100 | 101 | Unless required by applicable law or agreed to in writing, software 102 | distributed under the License is distributed on an "AS IS" BASIS, 103 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 104 | See the License for the specific language governing permissions and 105 | limitations under the License. 106 | ``` 107 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | maven { 6 | url "https://plugins.gradle.org/m2/" 7 | } 8 | } 9 | 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:7.0.0-rc01' 12 | 13 | // used to generate a POM file 14 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0' 15 | } 16 | } 17 | 18 | plugins { 19 | id "org.jetbrains.dokka" version "1.4.30" 20 | } 21 | 22 | allprojects { 23 | repositories { 24 | google() 25 | mavenCentral() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | org.gradle.parallel=true 19 | org.gradle.daemon=true 20 | org.gradle.configureondemand=true 21 | android.useAndroidX=true 22 | android.enableJetifier=true 23 | 24 | 25 | VERSION_NAME=1.10.0 26 | VERSION_CODE=5 27 | GROUP=com.pixplicity.easyprefs 28 | ARTIFACT_NAME=EasyPrefs 29 | ARTIFACT_ID=EasyPrefs 30 | POM_NAME=EasyPrefs 31 | POM_DESCRIPTION=Simple wrapper/helper for shared prefercences 32 | POM_ORGANIZATION=Pixplicity 33 | POM_URL=https://github.com/Pixplicity/EasyPreferences 34 | POM_SCM_URL=https://github.com/Pixplicity/EasyPreferences 35 | POM_ISSUE_URL=https://github.com/Pixplicity/EasyPreferences/issues 36 | POM_SCM_CONNECTION=scm:git@github.com:Pixplicity/EasyPreferences.git 37 | POM_SCM_DEV_CONNECTION=scm:git@github.com:Pixplicity/EasyPreferences.git 38 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 39 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 40 | POM_LICENCE_DIST=repo 41 | POM_DEVELOPER_ID_0=mathijs 42 | POM_DEVELOPER_NAME_0=Mathijs Lagerberg 43 | POM_DEVELOPER_EMAIL_0=mathijs@pixplicity.com 44 | 45 | BUILD_TOOLS=30.0.2 46 | COMPILE_SDK=30 47 | MIN_SDK=14 48 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pixplicity/EasyPrefs/8af206ae0cdd050cf8bf95f0f978540a6ad01986/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | } 6 | 7 | apply plugin: 'com.android.library' 8 | 9 | android { 10 | compileSdkVersion Integer.parseInt(COMPILE_SDK) 11 | 12 | defaultConfig { 13 | minSdkVersion Integer.parseInt(MIN_SDK) 14 | targetSdkVersion Integer.parseInt(COMPILE_SDK) 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | apply from: "${rootProject.projectDir}/mavencentral_publish.gradle" 25 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/dylan/opt/android-sdk-linux/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/pixplicity/easyprefs/library/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.pixplicity.easyprefs.library; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /library/src/main/java/com/pixplicity/easyprefs/library/Prefs.java: -------------------------------------------------------------------------------- 1 | package com.pixplicity.easyprefs.library; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.annotation.TargetApi; 5 | import android.content.Context; 6 | import android.content.ContextWrapper; 7 | import android.content.SharedPreferences; 8 | import android.content.SharedPreferences.Editor; 9 | import android.os.Build; 10 | import android.text.TextUtils; 11 | 12 | import java.util.LinkedHashSet; 13 | import java.util.Map; 14 | import java.util.Set; 15 | 16 | @SuppressWarnings("unused") 17 | public final class Prefs { 18 | 19 | private static final String DEFAULT_SUFFIX = "_preferences"; 20 | private static final String LENGTH = "#LENGTH"; 21 | private static SharedPreferences mPrefs; 22 | 23 | /** 24 | * Initialize the Prefs helper class to keep a reference to the SharedPreference for this 25 | * application the SharedPreference will use the package name of the application as the Key. 26 | * This method is deprecated please us the new builder. 27 | * 28 | * @param context the Application context. 29 | */ 30 | @Deprecated 31 | public static void initPrefs(Context context) { 32 | new Builder().setContext(context).build(); 33 | } 34 | 35 | private static void initPrefs(Context context, String prefsName, int mode) { 36 | mPrefs = context.getSharedPreferences(prefsName, mode); 37 | } 38 | 39 | /** 40 | * Returns the underlying SharedPreference instance 41 | * 42 | * @return an instance of the SharedPreference 43 | * @throws RuntimeException if SharedPreference instance has not been instantiated yet. 44 | */ 45 | @SuppressWarnings("WeakerAccess") 46 | public static SharedPreferences getPreferences() { 47 | if (mPrefs != null) { 48 | return mPrefs; 49 | } 50 | throw new RuntimeException( 51 | "Prefs class not correctly instantiated. Please call Builder.setContext().build() in the Application class onCreate."); 52 | } 53 | 54 | /** 55 | * @return Returns a map containing a list of pairs key/value representing 56 | * the preferences. 57 | * @see android.content.SharedPreferences#getAll() 58 | */ 59 | public static Map getAll() { 60 | return getPreferences().getAll(); 61 | } 62 | 63 | /** 64 | * Retrieves a stored int value. 65 | * 66 | * @param key The name of the preference to retrieve. 67 | * @param defValue Value to return if this preference does not exist. 68 | * @return Returns the preference value if it exists, or defValue. 69 | * @throws ClassCastException if there is a preference with this name that is not 70 | * an int. 71 | * @see android.content.SharedPreferences#getInt(String, int) 72 | */ 73 | public static int getInt(final String key, final int defValue) { 74 | return getPreferences().getInt(key, defValue); 75 | } 76 | 77 | /** 78 | * Retrieves a stored int value, or 0 if the preference does not exist. 79 | * 80 | * @param key The name of the preference to retrieve. 81 | * @return Returns the preference value if it exists, or 0. 82 | * @throws ClassCastException if there is a preference with this name that is not 83 | * an int. 84 | * @see android.content.SharedPreferences#getInt(String, int) 85 | */ 86 | public static int getInt(final String key) { 87 | return getPreferences().getInt(key, 0); 88 | } 89 | 90 | /** 91 | * Retrieves a stored boolean value. 92 | * 93 | * @param key The name of the preference to retrieve. 94 | * @param defValue Value to return if this preference does not exist. 95 | * @return Returns the preference value if it exists, or defValue. 96 | * @throws ClassCastException if there is a preference with this name that is not a boolean. 97 | * @see android.content.SharedPreferences#getBoolean(String, boolean) 98 | */ 99 | public static boolean getBoolean(final String key, final boolean defValue) { 100 | return getPreferences().getBoolean(key, defValue); 101 | } 102 | 103 | /** 104 | * Retrieves a stored boolean value, or false if the preference does not exist. 105 | * 106 | * @param key The name of the preference to retrieve. 107 | * @return Returns the preference value if it exists, or false. 108 | * @throws ClassCastException if there is a preference with this name that is not a boolean. 109 | * @see android.content.SharedPreferences#getBoolean(String, boolean) 110 | */ 111 | public static boolean getBoolean(final String key) { 112 | return getPreferences().getBoolean(key, false); 113 | } 114 | 115 | /** 116 | * Retrieves a stored long value. 117 | * 118 | * @param key The name of the preference to retrieve. 119 | * @param defValue Value to return if this preference does not exist. 120 | * @return Returns the preference value if it exists, or defValue. 121 | * @throws ClassCastException if there is a preference with this name that is not a long. 122 | * @see android.content.SharedPreferences#getLong(String, long) 123 | */ 124 | public static long getLong(final String key, final long defValue) { 125 | return getPreferences().getLong(key, defValue); 126 | } 127 | 128 | /** 129 | * Retrieves a stored long value, or 0 if the preference does not exist. 130 | * 131 | * @param key The name of the preference to retrieve. 132 | * @return Returns the preference value if it exists, or 0. 133 | * @throws ClassCastException if there is a preference with this name that is not a long. 134 | * @see android.content.SharedPreferences#getLong(String, long) 135 | */ 136 | public static long getLong(final String key) { 137 | return getPreferences().getLong(key, 0L); 138 | } 139 | 140 | /** 141 | * Returns the double that has been saved as a long raw bits value in the long preferences. 142 | * 143 | * @param key The name of the preference to retrieve. 144 | * @param defValue the double Value to return if this preference does not exist. 145 | * @return Returns the preference value if it exists, or defValue. 146 | * @throws ClassCastException if there is a preference with this name that is not a long. 147 | * @see android.content.SharedPreferences#getLong(String, long) 148 | */ 149 | public static double getDouble(final String key, final double defValue) { 150 | return Double.longBitsToDouble(getPreferences().getLong(key, Double.doubleToLongBits(defValue))); 151 | } 152 | 153 | /** 154 | * Returns the double that has been saved as a long raw bits value in the long preferences. 155 | * Returns 0 if the preference does not exist. 156 | * 157 | * @param key The name of the preference to retrieve. 158 | * @return Returns the preference value if it exists, or 0. 159 | * @throws ClassCastException if there is a preference with this name that is not a long. 160 | * @see android.content.SharedPreferences#getLong(String, long) 161 | */ 162 | public static double getDouble(final String key) { 163 | return Double.longBitsToDouble(getPreferences().getLong(key, Double.doubleToLongBits(0.0d))); 164 | } 165 | 166 | /** 167 | * Retrieves a stored float value. 168 | * 169 | * @param key The name of the preference to retrieve. 170 | * @param defValue Value to return if this preference does not exist. 171 | * @return Returns the preference value if it exists, or defValue. 172 | * @throws ClassCastException if there is a preference with this name that is not a float. 173 | * @see android.content.SharedPreferences#getFloat(String, float) 174 | */ 175 | public static float getFloat(final String key, final float defValue) { 176 | return getPreferences().getFloat(key, defValue); 177 | } 178 | 179 | /** 180 | * Retrieves a stored float value, or 0 if the preference does not exist. 181 | * 182 | * @param key The name of the preference to retrieve. 183 | * @return Returns the preference value if it exists, or 0. 184 | * @throws ClassCastException if there is a preference with this name that is not a float. 185 | * @see android.content.SharedPreferences#getFloat(String, float) 186 | */ 187 | public static float getFloat(final String key) { 188 | return getPreferences().getFloat(key, 0.0f); 189 | } 190 | 191 | /** 192 | * Retrieves a stored String value. 193 | * 194 | * @param key The name of the preference to retrieve. 195 | * @param defValue Value to return if this preference does not exist. 196 | * @return Returns the preference value if it exists, or defValue. 197 | * @throws ClassCastException if there is a preference with this name that is not a String. 198 | * @see android.content.SharedPreferences#getString(String, String) 199 | */ 200 | public static String getString(final String key, final String defValue) { 201 | return getPreferences().getString(key, defValue); 202 | } 203 | 204 | /** 205 | * Retrieves a stored String value, or an empty string if the preference does not exist. 206 | * 207 | * @param key The name of the preference to retrieve. 208 | * @return Returns the preference value if it exists, or "". 209 | * @throws ClassCastException if there is a preference with this name that is not a String. 210 | * @see android.content.SharedPreferences#getString(String, String) 211 | */ 212 | public static String getString(final String key) { 213 | return getPreferences().getString(key, ""); 214 | } 215 | 216 | /** 217 | * Retrieves a Set of Strings as stored by {@link #putStringSet(String, Set)}. On Honeycomb and 218 | * later this will call the native implementation in SharedPreferences, on older SDKs this will 219 | * call {@link #getOrderedStringSet(String, Set)}. 220 | * Note that the native implementation of {@link SharedPreferences#getStringSet(String, 221 | * Set)} does not reliably preserve the order of the Strings in the Set. 222 | * 223 | * @param key The name of the preference to retrieve. 224 | * @param defValue Value to return if this preference does not exist. 225 | * @return Returns the preference values if they exist, or defValues otherwise. 226 | * @throws ClassCastException if there is a preference with this name that is not a Set. 227 | * @see android.content.SharedPreferences#getStringSet(String, java.util.Set) 228 | * @see #getOrderedStringSet(String, Set) 229 | */ 230 | @SuppressWarnings("WeakerAccess") 231 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 232 | public static Set getStringSet(final String key, final Set defValue) { 233 | SharedPreferences prefs = getPreferences(); 234 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 235 | return prefs.getStringSet(key, defValue); 236 | } else { 237 | // Workaround for pre-HC's missing getStringSet 238 | return getOrderedStringSet(key, defValue); 239 | } 240 | } 241 | 242 | /** 243 | * Retrieves a Set of Strings as stored by {@link #putOrderedStringSet(String, Set)}, 244 | * preserving the original order. Note that this implementation is heavier than the native 245 | * {@link #getStringSet(String, Set)} method (which does not guarantee to preserve order). 246 | * 247 | * @param key The name of the preference to retrieve. 248 | * @param defValue Value to return if this preference does not exist. 249 | * @return Returns the preference value if it exists, or defValues otherwise. 250 | * @throws ClassCastException if there is a preference with this name that is not a Set of 251 | * Strings. 252 | * @see #getStringSet(String, Set) 253 | */ 254 | @SuppressWarnings("WeakerAccess") 255 | public static Set getOrderedStringSet(String key, final Set defValue) { 256 | SharedPreferences prefs = getPreferences(); 257 | if (prefs.contains(key + LENGTH)) { 258 | LinkedHashSet set = new LinkedHashSet<>(); 259 | int stringSetLength = prefs.getInt(key + LENGTH, -1); 260 | if (stringSetLength >= 0) { 261 | for (int i = 0; i < stringSetLength; i++) { 262 | set.add(prefs.getString(key + "[" + i + "]", null)); 263 | } 264 | } 265 | return set; 266 | } 267 | return defValue; 268 | } 269 | 270 | /** 271 | * Stores a long value. 272 | * 273 | * @param key The name of the preference to modify. 274 | * @param value The new value for the preference. 275 | * @see android.content.SharedPreferences.Editor#putLong(String, long) 276 | */ 277 | public static void putLong(final String key, final long value) { 278 | final Editor editor = getPreferences().edit(); 279 | editor.putLong(key, value); 280 | editor.apply(); 281 | } 282 | 283 | /** 284 | * Stores an integer value. 285 | * 286 | * @param key The name of the preference to modify. 287 | * @param value The new value for the preference. 288 | * @see android.content.SharedPreferences.Editor#putInt(String, int) 289 | */ 290 | public static void putInt(final String key, final int value) { 291 | final Editor editor = getPreferences().edit(); 292 | editor.putInt(key, value); 293 | editor.apply(); 294 | } 295 | 296 | /** 297 | * Stores a double value as a long raw bits value. 298 | * 299 | * @param key The name of the preference to modify. 300 | * @param value The double value to be save in the preferences. 301 | * @see android.content.SharedPreferences.Editor#putLong(String, long) 302 | */ 303 | public static void putDouble(final String key, final double value) { 304 | final Editor editor = getPreferences().edit(); 305 | editor.putLong(key, Double.doubleToRawLongBits(value)); 306 | editor.apply(); 307 | } 308 | 309 | /** 310 | * Stores a float value. 311 | * 312 | * @param key The name of the preference to modify. 313 | * @param value The new value for the preference. 314 | * @see android.content.SharedPreferences.Editor#putFloat(String, float) 315 | */ 316 | public static void putFloat(final String key, final float value) { 317 | final Editor editor = getPreferences().edit(); 318 | editor.putFloat(key, value); 319 | editor.apply(); 320 | } 321 | 322 | /** 323 | * Stores a boolean value. 324 | * 325 | * @param key The name of the preference to modify. 326 | * @param value The new value for the preference. 327 | * @see android.content.SharedPreferences.Editor#putBoolean(String, boolean) 328 | */ 329 | public static void putBoolean(final String key, final boolean value) { 330 | final Editor editor = getPreferences().edit(); 331 | editor.putBoolean(key, value); 332 | editor.apply(); 333 | } 334 | 335 | /** 336 | * Stores a String value. 337 | * 338 | * @param key The name of the preference to modify. 339 | * @param value The new value for the preference. 340 | * @see android.content.SharedPreferences.Editor#putString(String, String) 341 | */ 342 | public static void putString(final String key, final String value) { 343 | final Editor editor = getPreferences().edit(); 344 | editor.putString(key, value); 345 | editor.apply(); 346 | } 347 | 348 | /** 349 | * Stores a Set of Strings. On Honeycomb and later this will call the native implementation in 350 | * SharedPreferences.Editor, on older SDKs this will call {@link #putOrderedStringSet(String, 351 | * Set)}. 352 | * Note that the native implementation of {@link Editor#putStringSet(String, 353 | * Set)} does not reliably preserve the order of the Strings in the Set. 354 | * 355 | * @param key The name of the preference to modify. 356 | * @param value The new value for the preference. 357 | * @see android.content.SharedPreferences.Editor#putStringSet(String, java.util.Set) 358 | * @see #putOrderedStringSet(String, Set) 359 | */ 360 | @SuppressWarnings("WeakerAccess") 361 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 362 | public static void putStringSet(final String key, final Set value) { 363 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 364 | final Editor editor = getPreferences().edit(); 365 | editor.putStringSet(key, value); 366 | editor.apply(); 367 | } else { 368 | // Workaround for pre-HC's lack of StringSets 369 | putOrderedStringSet(key, value); 370 | } 371 | } 372 | 373 | /** 374 | * Stores a Set of Strings, preserving the order. 375 | * Note that this method is heavier that the native implementation {@link #putStringSet(String, 376 | * Set)} (which does not reliably preserve the order of the Set). To preserve the order of the 377 | * items in the Set, the Set implementation must be one that as an iterator with predictable 378 | * order, such as {@link LinkedHashSet}. 379 | * 380 | * @param key The name of the preference to modify. 381 | * @param value The new value for the preference. 382 | * @see #putStringSet(String, Set) 383 | * @see #getOrderedStringSet(String, Set) 384 | */ 385 | @SuppressWarnings("WeakerAccess") 386 | public static void putOrderedStringSet(String key, Set value) { 387 | final Editor editor = getPreferences().edit(); 388 | int stringSetLength = 0; 389 | if (mPrefs.contains(key + LENGTH)) { 390 | // First read what the value was 391 | stringSetLength = mPrefs.getInt(key + LENGTH, -1); 392 | } 393 | editor.putInt(key + LENGTH, value.size()); 394 | int i = 0; 395 | for (String aValue : value) { 396 | editor.putString(key + "[" + i + "]", aValue); 397 | i++; 398 | } 399 | for (; i < stringSetLength; i++) { 400 | // Remove any remaining values 401 | editor.remove(key + "[" + i + "]"); 402 | } 403 | editor.apply(); 404 | } 405 | 406 | /** 407 | * Removes a preference value. 408 | * 409 | * @param key The name of the preference to remove. 410 | * @see android.content.SharedPreferences.Editor#remove(String) 411 | */ 412 | public static void remove(final String key) { 413 | SharedPreferences prefs = getPreferences(); 414 | final Editor editor = prefs.edit(); 415 | if (prefs.contains(key + LENGTH)) { 416 | // Workaround for pre-HC's lack of StringSets 417 | int stringSetLength = prefs.getInt(key + LENGTH, -1); 418 | if (stringSetLength >= 0) { 419 | editor.remove(key + LENGTH); 420 | for (int i = 0; i < stringSetLength; i++) { 421 | editor.remove(key + "[" + i + "]"); 422 | } 423 | } 424 | } 425 | editor.remove(key); 426 | 427 | editor.apply(); 428 | } 429 | 430 | /** 431 | * Checks if a value is stored for the given key. 432 | * 433 | * @param key The name of the preference to check. 434 | * @return {@code true} if the storage contains this key value, {@code false} otherwise. 435 | * @see android.content.SharedPreferences#contains(String) 436 | */ 437 | public static boolean contains(final String key) { 438 | return getPreferences().contains(key); 439 | } 440 | 441 | /** 442 | * Removed all the stored keys and values. 443 | * 444 | * @return the {@link Editor} for chaining. The changes have already been committed/applied 445 | * through the execution of this method. 446 | * @see android.content.SharedPreferences.Editor#clear() 447 | */ 448 | public static Editor clear() { 449 | final Editor editor = getPreferences().edit().clear(); 450 | editor.apply(); 451 | return editor; 452 | } 453 | 454 | /** 455 | * Returns the Editor of the underlying SharedPreferences instance. 456 | * 457 | * @return An Editor 458 | */ 459 | public static Editor edit() { 460 | return getPreferences().edit(); 461 | } 462 | 463 | /** 464 | * Builder class for the EasyPrefs instance. You only have to call this once in the Application 465 | * onCreate. And in the rest of the code base you can call Prefs.method name. 466 | */ 467 | public final static class Builder { 468 | 469 | private String mKey; 470 | private Context mContext; 471 | private int mMode = -1; 472 | private boolean mUseDefault = false; 473 | 474 | /** 475 | * Set the filename of the SharedPreference instance. Usually this is the application's 476 | * packagename.xml but it can be modified for migration purposes or customization. 477 | * 478 | * @param prefsName the filename used for the SharedPreference 479 | * @return the {@link com.pixplicity.easyprefs.library.Prefs.Builder} object. 480 | */ 481 | public Builder setPrefsName(final String prefsName) { 482 | mKey = prefsName; 483 | return this; 484 | } 485 | 486 | /** 487 | * Set the Context used to instantiate the SharedPreferences 488 | * 489 | * @param context the application context 490 | * @return the {@link com.pixplicity.easyprefs.library.Prefs.Builder} object. 491 | */ 492 | public Builder setContext(final Context context) { 493 | mContext = context; 494 | return this; 495 | } 496 | 497 | /** 498 | * Set the mode of the SharedPreference instance. 499 | * 500 | * @param mode Operating mode. Use 0 or {@link Context#MODE_PRIVATE} for the 501 | * default operation, {@link Context#MODE_WORLD_READABLE} 502 | * @return the {@link com.pixplicity.easyprefs.library.Prefs.Builder} object. 503 | * @see Context#getSharedPreferences 504 | */ 505 | @SuppressLint({"WorldReadableFiles", "WorldWriteableFiles"}) 506 | public Builder setMode(final int mode) { 507 | if (mode == ContextWrapper.MODE_PRIVATE || mode == ContextWrapper.MODE_WORLD_READABLE || mode == ContextWrapper.MODE_WORLD_WRITEABLE || mode == ContextWrapper.MODE_MULTI_PROCESS) { 508 | mMode = mode; 509 | } else { 510 | throw new RuntimeException("The mode in the SharedPreference can only be set too ContextWrapper.MODE_PRIVATE, ContextWrapper.MODE_WORLD_READABLE, ContextWrapper.MODE_WORLD_WRITEABLE or ContextWrapper.MODE_MULTI_PROCESS"); 511 | } 512 | 513 | return this; 514 | } 515 | 516 | /** 517 | * Set the default SharedPreference file name. Often the package name of the application is 518 | * used, but if the {@link android.preference.PreferenceActivity} or {@link 519 | * android.preference.PreferenceFragment} is used the system will append that with 520 | * _preference. 521 | * 522 | * @param defaultSharedPreference true if default SharedPreference name should used. 523 | * @return the {@link com.pixplicity.easyprefs.library.Prefs.Builder} object. 524 | */ 525 | @SuppressWarnings("SameParameterValue") 526 | public Builder setUseDefaultSharedPreference(boolean defaultSharedPreference) { 527 | mUseDefault = defaultSharedPreference; 528 | return this; 529 | } 530 | 531 | /** 532 | * Initialize the SharedPreference instance to used in the application. 533 | * 534 | * @throws RuntimeException if Context has not been set. 535 | */ 536 | public void build() { 537 | if (mContext == null) { 538 | throw new RuntimeException("Context not set, please set context before building the Prefs instance."); 539 | } 540 | 541 | if (TextUtils.isEmpty(mKey)) { 542 | mKey = mContext.getPackageName(); 543 | } 544 | 545 | if (mUseDefault) { 546 | mKey += DEFAULT_SUFFIX; 547 | } 548 | 549 | if (mMode == -1) { 550 | mMode = ContextWrapper.MODE_PRIVATE; 551 | } 552 | 553 | Prefs.initPrefs(mContext, mKey, mMode); 554 | } 555 | 556 | } 557 | 558 | } 559 | -------------------------------------------------------------------------------- /library/src/main/res/values/about_easypreferences_strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Pixplicity 7 | http://pixplicity.com 8 | 9 | EasyPreferences 10 | A small library containing a wrapper/helper for the Shared Preferences of Android 11 | https://github.com/Pixplicity/EasyPreferences 12 | 3.2.1 13 | 14 | true 15 | https://github.com/Pixplicity/EasyPreferences 16 | 17 | com.pixplicity.easyprefs.library 18 | 19 | apache_2_0 20 | 21 | 22 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /mavencentral_publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | apply plugin: 'signing' 3 | 4 | task androidSourcesJar(type: Jar) { 5 | archiveClassifier.set('sources') 6 | if (project.plugins.findPlugin("com.android.library")) { 7 | from android.sourceSets.main.java.srcDirs 8 | //from android.sourceSets.main.kotlin.srcDirs 9 | } else { 10 | from sourceSets.main.java.srcDirs 11 | from sourceSets.main.kotlin.srcDirs 12 | } 13 | } 14 | 15 | artifacts { 16 | archives androidSourcesJar 17 | //archives javadocJar 18 | } 19 | 20 | // Note: these lines are important, even though they're not used in this file! 21 | // The plugin looks for it. 22 | group = GROUP 23 | version = VERSION_NAME 24 | 25 | ext["signing.keyId"] = '' 26 | ext["signing.password"] = '' 27 | ext["signing.secretKeyRingFile"] = '' 28 | ext["ossrhUsername"] = '' 29 | ext["ossrhPassword"] = '' 30 | ext["sonatypeStagingProfileId"] = '' 31 | 32 | File secretPropsFile = project.rootProject.file('.signing/mavencentral.properties') 33 | if (secretPropsFile.exists()) { 34 | Properties p = new Properties() 35 | p.load(new FileInputStream(secretPropsFile)) 36 | p.each { name, value -> 37 | ext[name] = value 38 | } 39 | } else { 40 | ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') 41 | ext["signing.password"] = System.getenv('SIGNING_PASSWORD') 42 | ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') 43 | ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') 44 | ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') 45 | ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') 46 | } 47 | 48 | publishing { 49 | publications { 50 | release(MavenPublication) { 51 | groupId GROUP 52 | artifactId ARTIFACT_ID 53 | version VERSION_NAME 54 | 55 | if (project.plugins.findPlugin("com.android.library")) { 56 | artifact("$buildDir/outputs/aar/${project.getName()}-release.aar") 57 | } else { 58 | artifact("$buildDir/libs/${project.getName()}-${version}.jar") 59 | } 60 | 61 | artifact androidSourcesJar 62 | 63 | pom { 64 | name = ARTIFACT_ID 65 | description = POM_DESCRIPTION 66 | url = POM_SCM_URL 67 | licenses { 68 | license { 69 | name = POM_LICENCE_NAME 70 | url = POM_LICENCE_URL 71 | } 72 | } 73 | developers { 74 | developer { 75 | id = POM_DEVELOPER_ID_0 76 | name = POM_DEVELOPER_NAME_0 77 | email = POM_DEVELOPER_EMAIL_0 78 | } 79 | } 80 | scm { 81 | connection = POM_SCM_CONNECTION 82 | developerConnection = POM_SCM_DEV_CONNECTION 83 | url = POM_SCM_URL 84 | } 85 | withXml { 86 | def dependenciesNode = asNode().appendNode('dependencies') 87 | 88 | project.configurations.implementation.allDependencies.each { 89 | def dependencyNode = dependenciesNode.appendNode('dependency') 90 | dependencyNode.appendNode('groupId', it.group) 91 | dependencyNode.appendNode('artifactId', it.name) 92 | dependencyNode.appendNode('version', it.version) 93 | } 94 | } 95 | } 96 | } 97 | } 98 | repositories { 99 | maven { 100 | name = "sonatype" 101 | url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 102 | 103 | credentials { 104 | username ossrhUsername 105 | password ossrhPassword 106 | } 107 | } 108 | } 109 | } 110 | 111 | signing { 112 | sign publishing.publications 113 | } 114 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion Integer.parseInt(COMPILE_SDK) 5 | buildToolsVersion BUILD_TOOLS 6 | 7 | compileOptions { 8 | sourceCompatibility JavaVersion.VERSION_1_7 9 | targetCompatibility JavaVersion.VERSION_1_7 10 | } 11 | 12 | defaultConfig { 13 | applicationId "com.pixplicity.easyprefs.sample" 14 | minSdkVersion Integer.parseInt(MIN_SDK) 15 | targetSdkVersion Integer.parseInt(COMPILE_SDK) 16 | versionCode Integer.parseInt(VERSION_CODE) 17 | versionName VERSION_NAME 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | } 26 | 27 | dependencies { 28 | implementation project(':library') 29 | 30 | implementation 'com.android.support:appcompat-v7:28.0.0' 31 | 32 | } 33 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/dylan/opt/android-sdk-linux/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/pixplicity/easyprefs/sample/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.pixplicity.easyprefs.sample; 2 | 3 | import android.test.ApplicationTestCase; 4 | 5 | /** 6 | * Testing Fundamentals 7 | */ 8 | public class ApplicationTest extends ApplicationTestCase { 9 | public ApplicationTest() { 10 | super(PrefsApplication.class); 11 | } 12 | 13 | 14 | 15 | 16 | } -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /sample/src/main/java/com/pixplicity/easyprefs/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.pixplicity.easyprefs.sample; 2 | 3 | import android.os.Bundle; 4 | import android.text.TextUtils; 5 | import android.view.View; 6 | import android.widget.EditText; 7 | import android.widget.TextView; 8 | import android.widget.Toast; 9 | 10 | import androidx.annotation.NonNull; 11 | import androidx.appcompat.app.AppCompatActivity; 12 | 13 | import com.pixplicity.easyprefs.library.Prefs; 14 | 15 | public class MainActivity extends AppCompatActivity { 16 | 17 | public static final String SAVED_TEXT = "saved_text"; 18 | public static final String SAVED_NUMBER = "saved_number"; 19 | private static final String FROM_INSTANCE_STATE = " : from instance state"; 20 | 21 | TextView mSavedText; 22 | TextView mSavedNumber; 23 | EditText mTextET; 24 | EditText mNumberET; 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | setContentView(R.layout.activity_main); 30 | 31 | mSavedText = findViewById(R.id.tv_saved_text); 32 | mSavedNumber = findViewById(R.id.tv_saved_number); 33 | mTextET = findViewById(R.id.et_text); 34 | mNumberET = findViewById(R.id.et_number); 35 | 36 | // get the saved String from the preference by key, and give a default value 37 | // if Prefs does not contain the key. 38 | String s = Prefs.getString(SAVED_TEXT, getString(R.string.not_found)); 39 | double d = Prefs.getDouble(SAVED_NUMBER, -1.0); 40 | updateText(s); 41 | updateNumber(d, false); 42 | 43 | findViewById(R.id.bt_save_text).setOnClickListener(new View.OnClickListener() { 44 | 45 | @Override 46 | public void onClick(View v) { 47 | String text = mTextET.getText().toString(); 48 | if (!TextUtils.isEmpty(text)) { 49 | // one liner to save the String. 50 | Prefs.putString(SAVED_TEXT, text); 51 | updateText(text); 52 | } else { 53 | Toast.makeText(MainActivity.this, "trying to save a text with lenght 0", Toast.LENGTH_SHORT).show(); 54 | } 55 | } 56 | }); 57 | 58 | findViewById(R.id.bt_save_number).setOnClickListener(new View.OnClickListener() { 59 | 60 | @Override 61 | public void onClick(View v) { 62 | double d = Double.parseDouble(mNumberET.getText().toString()); 63 | Prefs.putDouble(SAVED_NUMBER, d); 64 | updateNumber(d, false); 65 | } 66 | }); 67 | 68 | findViewById(R.id.bt_force_close).setOnClickListener(new View.OnClickListener() { 69 | 70 | @Override 71 | public void onClick(View v) { 72 | finish(); 73 | } 74 | }); 75 | } 76 | 77 | private void updateText(String s) { 78 | String text = String.format(getString(R.string.saved_text), s); 79 | mSavedText.setText(text); 80 | } 81 | 82 | private void updateNumber(double d, boolean fromInstanceState) { 83 | String text = String.format(getString(R.string.saved_number), String.valueOf(d), fromInstanceState ? FROM_INSTANCE_STATE : ""); 84 | mSavedNumber.setText(text); 85 | } 86 | 87 | @Override 88 | protected void onSaveInstanceState(Bundle outState) { 89 | super.onSaveInstanceState(outState); 90 | final String text = mTextET.getText().toString(); 91 | if (!TextUtils.isEmpty(text)) { 92 | outState.putString(SAVED_TEXT, text); 93 | } 94 | double d = Double.parseDouble(mNumberET.getText().toString()); 95 | outState.putDouble(SAVED_NUMBER, d); 96 | } 97 | 98 | @Override 99 | protected void onRestoreInstanceState(@NonNull Bundle state) { 100 | super.onRestoreInstanceState(state); 101 | if (state.containsKey(SAVED_TEXT)) { 102 | final String text = state.getString(SAVED_TEXT) + FROM_INSTANCE_STATE; 103 | updateText(text); 104 | } 105 | 106 | if (state.containsKey(SAVED_NUMBER)) { 107 | double d = state.getDouble(SAVED_NUMBER); 108 | updateNumber(d, true); 109 | } 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /sample/src/main/java/com/pixplicity/easyprefs/sample/PrefsApplication.java: -------------------------------------------------------------------------------- 1 | package com.pixplicity.easyprefs.sample; 2 | 3 | 4 | import android.app.Application; 5 | import android.content.ContextWrapper; 6 | 7 | import com.pixplicity.easyprefs.library.Prefs; 8 | 9 | public class PrefsApplication extends Application { 10 | 11 | @Override 12 | public void onCreate() { 13 | super.onCreate(); 14 | // Initialize the Prefs class 15 | new Prefs.Builder() 16 | .setContext(this) 17 | .setMode(ContextWrapper.MODE_PRIVATE) 18 | .setPrefsName(getPackageName()) 19 | .setUseDefaultSharedPreference(true) 20 | .build(); 21 | } 22 | } -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 17 | 18 | 24 | 25 | 26 | 31 | 32 | 39 | 40 |