• Stars
    star
    378
  • Rank 109,201 (Top 3 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿšš Android processing library for managing SharedPreferences persistence efficiently and structurally.

PreferenceRoom

License API Android CI Android Weekly

PreferenceRoom is an android annotation processor library to manage SharedPreferences more efficiently and structurally. PreferenceRoom was inspired by Architecture Components Room Persistence and dagger. PreferenceRoom integrates scattered SharedPreferences as a single entity and it supports custom setter/getter functions with security algorithm. Also this library provides simple dependency injection system, which is free from reflection, and fully-supported in kotlin project.

Who's using this library?

GithubFollows
Open Source
All-In-One
Open Source
Battle Comics
Product
Epoptia
Open Source
Sensemore
Octocat allinone battleent epoptia Sensemore

Download

Maven Central

Gradle

Add the codes below to your root build.gradle file (not your module build.gradle file).

allprojects {
    repositories {
        mavenCentral()
    }
}

And add the dependency below to your module's build.gradle file.

dependencies {
    implementation "com.github.skydoves:preferenceroom:1.2.2"
    annotationProcessor "com.github.skydoves:preferenceroom-processor:1.2.2"
    // in kotlin project use kapt instead of annotationProcessor
    kapt "com.github.skydoves:preferenceroom-processor:1.2.2"
}

Table of Contents

1.PreferenceEntity

2.PreferenceComponent

3.Dependency Injection (Use with dagger)

4.Usage in Kotlin (Incremental annotation processing)

5.Proguard-Rules

6.Debugging with Stetho

PreferenceEntity

preferenceentity
@PreferenceEntity annotation makes SharedPreferences data as an entity.
Value in @PreferenceEntity determines the entity name.
Entity's default name is determined by class name.

@PreferenceEntity("UserProfile")
public class Profile {
    protected final boolean login = false;
    @KeyName("nickname") protected final String userNickName = null;
    @KeyName("visits") protected final int visitCount = 1;

    @KeyName("userPet")
    @TypeConverter(PetConverter.class)
    protected Pet userPetInfo;

    @PreferenceFunction("nickname")
    public String putUserNickFunction(String nickname) {
        return "Hello, " + nickname;
    }

    @PreferenceFunction("nickname")
    public String getUserNickFunction(String nickname) {
        return nickname + "!!!";
    }

    @PreferenceFunction("visits")
    public int putVisitCountFunction(int count) {
        return ++count;
    }
}

After the build your project, Preference_(entity name) class will be generated automatically.

Preference_UserProfile userProfile = Preference_UserProfile.getInstance(this); // gets instance of the UserProfile entity.
userProfile.putNickname("my nickname"); // puts a value in NickName.
userProfile.getNickname(); // gets a nickname value.
userProfile.containsNickname(); // checks nickname key value is exist or not in entity.
userProfile.removeNickname(); // removes nickname key value in entity.
userProfile.nicknameKeyName(); // returns nickname key name.
userProfile.getEntityName(); // returns UserProfile entity name;
userProfile.getkeyNameList(); // returns UserProfile entity's key name lists.

// or invoke static.
Preference_UserProfile.getInstance(this).putNickname("my nickname");

we can listen the changed value using OnChangedListener.
onChanged method will be invoked if we change the value using put method.

userProfile.addNicknameOnChangedListener(new Preference_UserProfile.NicknameOnChangedListener() {
   @Override
   public void onChanged(String nickname) {
     Toast.makeText(getBaseContext(), "onChanged :" + nickname, Toast.LENGTH_SHORT).show();
   }
});

Auto-generated code is managed by singletons.
But we can manage more efficiently using PreferenceComponent and Dependency Injection.

We can set SharedPreference to an entity as DefaultSharedPreferences using @DefaultPreference annotation like below.

@DefaultPreference
@PreferenceEntity("ProfileWithDefault")
public class UserProfilewithDefaultPreference {
    @KeyName("nickname")
    protected final String userNickName = "skydoves";
    
    // key name will be 'Login'. (login's camel uppercase)
    protected final boolean login = false;
}

The ProfileWithDefault entity from the example, will be initialized like below on PreferenceRoom processor.

PreferenceManager.getDefaultSharedPreferences(context);

So we can connect with PreferenceFragmentCompat, PreferenceScreen or etc.

KeyName

keyname
@KeyName annotation can be used on an entity class's field.
The field's key name will be decided by field name, but we can customize the name as taste.

@KeyName("visits") // keyname will be Visits.
protected final int visitCount = 1;

TypeConverter

typeconverter
SharedPreference persists only primitive type data.
But PreferenceRoom supports persistence obejct data using TypeConverter annotation.
@TypeConverter annotation should be annotated over an object field like below.

@TypeConverter(PetConverter.class)
protected Pet userPetInfo; // 'Pet' class field in an entity.

Below example is creating a converter class using Gson.
Converter class should extends the PreferenceTypeConverter<?> class.
The basic principle is making object class to string data for persistence and getting the string data and recover.
convertObject performs how to change class data to a string, convertType performs how to recover class data from the string data.

public class PetConverter extends PreferenceTypeConverter<Pet> {

    private final Gson gson;

    // default constructor will be called by PreferenceRoom
    public PetConverter() {
        this.gson = new Gson();
    }

    @Override
    public String convertObject(Pet pet) {
        return gson.toJson(pet);
    }

    @Override
    public Pet convertType(String string) {
        return gson.fromJson(string, Pet.class);
    }
}

BaseTypeConverter

We can generalize the converter using generic like below.

public class BaseGsonConverter<T> extends PreferenceTypeConverter<T> {

    private final Gson gson;

    public BaseGsonConverter(Class<T> clazz) {
        super(clazz);
        this.gson = new Gson();
    }

    @Override
    public String convertObject(T object) {
        return gson.toJson(object);
    }

    @Override
    public T convertType(String string) {
        return gson.fromJson(string, clazz);
    }
}

So we can use the converter to any classes.

@KeyName("userinfo")
@TypeConverter(BaseGsonConverter.class)
protected PrivateInfo privateInfo;

@KeyName("userPet")
@TypeConverter(BaseGsonConverter.class)
protected Pet userPetInfo;

PreferenceFunction

preferencefunction
@PreferenceFunction annotation processes pre/post-processing through getter and setter functions.
@PreferenceFunction annotation's value decides a target. The target should be a keyName.
The function's naming convention is which should start with put or get prefix.
put_functionname_ is pre-processing getter function and get_functionname_ is postprocessing getter function.

@PreferenceFunction("nickname")
public String putUserNickFunction(String nickname) {
    return "Hello, " + nickname;
}

@PreferenceFunction("nickname")
public String getUserNickFunction(String nickname) {
    return nickname + "!!!";
}

EncryptEntity

SharedPreferences data are not safe from hacking even if private-mode.
There is a simple way to encrypt whole entity using @EncryptEntity annotation.
It is based on AES128 encryption. So we should set the key value along 16 size length.
If put method invoked, the value is encrypted automatically.
And if get method invoked, it returns the decrypted value.

@EncryptEntity("1234567890ABCDFG")
@PreferenceEntity("UserProfile")
public class Profile {
}

Or we can customize encrypting and decrypting algorithm using PreferenceFunction.

@PreferenceFunction("uuid")
public String putUuidFunction(String uuid) {
   return SecurityUtils.encrypt(uuid);
}

@PreferenceFunction("uuid")
public String getUuidFunction(String uuid) {
    return SecurityUtils.decrypt(uuid);
}

PreferenceComponent

preferencecomponent
PreferenceComponent integrates entities. @PreferenceComponent annotation should be annotated on an interface class.
We can integrate many entities as one component using entities value in @PreferenceComponent annotation.
So we can initialize many entities at once through the component and get instances from the component.
And the instance of the PreferenceComponent is managed by singleton by PreferenceRoom. `PreferenceComponent's instance also singletons. And all entities instances are initialized when the component is initialized.

@PreferenceComponent(entities = {Profile.class, Device.class})
public interface UserProfileComponent {
}

After build your project, PreferenceComponent_(component's name) class will be generated automatically.
The best-recommanded way to initialize component is initializing on Application class. So we can manage the component as a singleton instance.

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        PreferenceComponent_UserProfileComponent.init(this);
    }
}

After initializing the component, we can access and use the instances of component and component's entities anywhere.

PreferenceComponent_UserProfileComponent component = PreferenceComponent_UserProfileComponent.getInstance();
Preference_UserProfile userProfile = component.UserProfile();
Preference_UserDevice userDevice = PreferenceComponent_UserProfileComponent.getInstance().UserDevice();

Dependency Injection

di
PreferenceRoom supports simple dependency injection process with free from reflection using @InjectPreference annotation. But If you want to use with dagger, check this reference.

Firstly we should declare some target classes which to be injected preference instances in PreferenceComponent.

@PreferenceComponent(entities = {Profile.class, Device.class})
public interface UserProfileComponent {
    // declares targets for the dependency injection.
    void inject(MainActivity __);
    void inject(LoginActivity __);
}

We should annotate InjectPreference annotation to preference entity or component class field which generated by PreferenceRoom.
The field's modifier should be public.

@InjectPreference
public PreferenceComponent_UserProfileComponent component;

@InjectPreference
public Preference_UserProfile userProfile;

And the last, we should inject instances of entity and component to targets fields using inject method from an instance of the component.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   PreferenceComponent_UserProfileComponent.getInstance().inject(this);
}

Usage in Kotlin

It is similar to java project usage.
But the most important thing is which we should use an open modifier on entity classes and PreferenceFunctions.
And the field's modifier should be @JvmField val.

@PreferenceEntity("UserDevice")
open class Device {
    @KeyName("version")
    @JvmField val deviceVersion: String? = null

    @KeyName("uuid")
    @JvmField val userUUID: String? = null

    @PreferenceFunction("uuid")
    open fun putUuidFunction(uuid: String?): String? {
        return SecurityUtils.encrypt(uuid)
    }

    @PreferenceFunction( "uuid")
    open fun getUuidFunction(uuid: String?): String? {
        return SecurityUtils.decrypt(uuid)
    }
}

And the component usage is almost the same as Java examples.

@PreferenceComponent(entities = [Profile::class, Device::class])
interface UserProfileComponent {
    // declare dependency injection targets.
    fun inject(target: MainActivity)
    fun inject(target: LoginActivity)
}

And the last, the usage of the dependency injection is the same as the java. but we should declare the component and entity field's modifier as lateinit var.

@InjectPreference
lateinit var component: PreferenceComponent_UserProfileComponent
    
override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   setContentView(R.layout.activity_main)
    PreferenceComponent_UserProfileComponent.getInstance().inject(this) // inject dependency injection to MainActivity.

Incremetal annotation processing

Starting from version 1.3.30, kapt supports incremental annotation processing as an experimental feature. Currently, annotation processing can be incremental only if all annotation processors being used are incremental.
Incremental annotation processing is enabled by default starting from version 1.3.50.
PreferenceRoom supports incremental annotation processing since version 1.1.9 and here is a Before/After example result of the enabled.

Before (23.758s) After (18.779s)

Non Existent Type Correction

If you encounter NonExistentClass error at compile time, you should add below codes on your build.gradle.
Default, Kapt replaces every unknown type (including types for the generated classes) to NonExistentClass, but you can change this behavior. Add the additional flag to the build.gradle file to enable error type inferring in stubs:

kapt {
  correctErrorTypes = true
}

Proguard Rules

# Retain generated class which implement PreferenceRoomImpl.
-keep public class ** implements com.skydoves.preferenceroom.PreferenceRoomImpl

# Prevent obfuscation of types which use PreferenceRoom annotations since the simple name
# is used to reflectively look up the generated Injector.
-keep class com.skydoves.preferenceroom.*
-keepclasseswithmembernames class * { @com.skydoves.preferenceroom.* <methods>; }
-keepclasseswithmembernames class * { @com.skydoves.preferenceroom.* <fields>; }

Debugging with Stetho

We can debug SharedPreferences values which managed by PreferenceRoom using Stetho.
screenshot635705571

References

Find this library useful? โค๏ธ

Support it by joining stargazers for this repository. โญ

Sponsor โ˜•

If you feel like to sponsor me a coffee for my efforts, I would greatly appreciate it.

Buy Me A Coffee

License

Copyright 2017 skydoves

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.

More Repositories

1

Pokedex

๐Ÿ—ก๏ธ Pokedex demonstrates modern Android development with Hilt, Material Motion, Coroutines, Flow, Jetpack (Room, ViewModel) based on MVVM architecture.
Kotlin
7,496
star
2

android-developer-roadmap

๐Ÿ—บ The Android Developer Roadmap offers comprehensive learning paths to help you understand Android ecosystems.
Kotlin
6,880
star
3

Balloon

๐ŸŽˆ Modernized and sophisticated tooltips, fully customizable with an arrow and animations for Android.
Kotlin
3,535
star
4

chatgpt-android

๐Ÿ“ฒ ChatGPT Android demonstrates OpenAI's ChatGPT on Android with Stream Chat SDK for Compose.
Kotlin
3,460
star
5

TransformationLayout

๐ŸŒ  Transform between two Views, Activities, and Fragments, or a View to a Fragment with container transform animations for Android.
Kotlin
2,279
star
6

landscapist

๐ŸŒป A pluggable, highly optimized Jetpack Compose and Kotlin Multiplatform image loading library that fetches and displays network images with Glide, Coil, and Fresco.
Kotlin
1,876
star
7

ColorPickerView

๐ŸŽจ Android colorpicker for getting colors from any images by tapping on the desired color.
Java
1,503
star
8

DisneyMotions

๐Ÿฆ A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, Room, Repository, Koin) architecture.
Kotlin
1,482
star
9

sandwich

๐Ÿฅช Sandwich is an adaptable and lightweight sealed API library designed for handling API responses and exceptions in Kotlin for Retrofit, Ktor, and Kotlin Multiplatform.
Kotlin
1,403
star
10

AndroidVeil

๐ŸŽญ An easy, flexible way to implement loading skeletons and shimmering effect for Android.
Kotlin
1,384
star
11

MarvelHeroes

โค๏ธ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, Room, Repository, Koin) architecture.
Kotlin
1,224
star
12

PowerMenu

๐Ÿ”ฅ Powerful and modernized popup menu with fully customizable animations.
Java
1,163
star
13

PowerSpinner

๐ŸŒ€ A lightweight dropdown popup spinner, fully customizable with an arrow and animations for Android.
Kotlin
1,105
star
14

Orbital

๐Ÿช Jetpack Compose Multiplatform library that allows you to implement dynamic transition animations such as shared element transitions.
Kotlin
989
star
15

DisneyCompose

๐Ÿงธ A demo Disney app using Jetpack Compose and Hilt based on modern Android tech stacks and MVVM architecture.
Kotlin
929
star
16

WhatIf

โ˜” Fluent syntactic sugar of Kotlin for handling single if-else statements, nullable, collections, and booleans.
Kotlin
835
star
17

ExpandableLayout

๐Ÿฆš An expandable layout that shows a two-level layout with an indicator.
Kotlin
809
star
18

ElasticViews

โœจ An easy way to implement an elastic touch effect for Android.
Kotlin
784
star
19

ProgressView

๐ŸŒŠ A polished and flexible ProgressView, fully customizable with animations.
Kotlin
755
star
20

AndroidRibbon

๐ŸŽ€ A fancy and beautiful ribbon with shimmer effects for Android.
Kotlin
684
star
21

Cloudy

โ˜๏ธ Jetpack Compose blur effect library, which falls back onto a CPU-based implementation to support older API levels.
Kotlin
639
star
22

Needs

๐ŸŒ‚ An easy way to implement modern permission instructions popup.
Kotlin
616
star
23

Pokedex-AR

๐Ÿฆ„ Pokedex-AR demonstrates ARCore, Sceneform, and modern Android tech stacks โ€” such as Hilt, Coroutines, Flow, Jetpack (Room, ViewModel, LiveData) based on MVVM architecture.
Kotlin
582
star
24

FlexibleBottomSheet

๐Ÿฌ Advanced Compose Multiplatform bottom sheet for segmented sizing and non-modal type, similar to Google Maps.
Kotlin
541
star
25

Only

๐Ÿ’ An easy way to persist and run code block only as many times as necessary on Android.
Kotlin
485
star
26

TheMovies

๐ŸŽฌ A demo project for The Movie DB based on Kotlin MVVM architecture and material design & animations.
Kotlin
484
star
27

MovieCompose

๐ŸŽž A demo movie app using Jetpack Compose and Hilt based on modern Android tech stacks.
Kotlin
475
star
28

ColorPickerPreference

๐ŸŽจ A library that lets you implement ColorPicker, ColorPickerDialog, ColorPickerPreference.
Kotlin
474
star
29

TheMovies2

๐ŸŽฌ A demo project using The Movie DB based on Kotlin MVVM architecture and material design & animations.
Kotlin
474
star
30

Submarine

๐Ÿšค Floating navigation view for displaying a list of items dynamically on Android.
Kotlin
471
star
31

retrofit-adapters

๐Ÿš† Retrofit call adapters for modeling network responses using Kotlin Result, Jetpack Paging3, and Arrow Either.
Kotlin
462
star
32

Rainbow

๐ŸŒˆ Fluent syntactic sugar of Android for applying gradations, shading, and tinting.
Kotlin
451
star
33

Orchestra

๐ŸŽบ A collection of Jetpack Compose libraries, which allows you to build tooltips, spinners, and color pickers.
Kotlin
447
star
34

IndicatorScrollView

๐Ÿง€ A dynamic scroll view that animates indicators according to its scroll position.
Kotlin
415
star
35

colorpicker-compose

๐ŸŽจ Jetpack Compose color picker library for getting colors from any images by tapping on the desired color.
Kotlin
370
star
36

DoubleLift

๐Ÿฆ‹ Expands and collapses a layout horizontally and vertically sequentially.
Kotlin
360
star
37

GoldMovies

๐Ÿ‘‘ The GoldMovies is based on Kotlin, MVVM architecture, coroutines, dagger, koin, and material designs & animations.
Kotlin
354
star
38

lazybones

๐Ÿ˜ด A lazy and fluent syntactic sugar for observing Activity, Fragment, and ViewModel lifecycles with lifecycle-aware properties.
Kotlin
351
star
39

sealedx

๐ŸŽฒ Kotlin Symbol Processor that auto-generates extensive sealed classes and interfaces for Android and Kotlin.
Kotlin
316
star
40

Bindables

๐Ÿงฌ Android DataBinding kit for notifying data changes to UI layers with MVVM architecture.
Kotlin
304
star
41

AndroidBottomBar

๐Ÿซ A lightweight bottom navigation view, fully customizable with an indicator and animations.
Kotlin
297
star
42

GithubFollows

:octocat: A demo project based on MVVM architecture and material design & animations.
Kotlin
293
star
43

Bundler

๐ŸŽ Android Intent & Bundle extensions that insert and retrieve values elegantly.
Kotlin
262
star
44

gemini-android

โœจ Gemini Android demonstrates Google's Generative AI on Android with Stream Chat SDK for Compose.
Kotlin
262
star
45

snitcher

๐Ÿฆ‰ Snitcher captures global crashes, enabling easy redirection to the exception tracing screen for swift recovery.
Kotlin
216
star
46

Chamber

โš–๏ธ A lightweight Android lifecycle-aware and thread-safe pipeline for communicating between components with custom scopes.
Kotlin
185
star
47

twitch-clone-compose

๐ŸŽฎ Twitch clone project demonstrates modern Android development built with Jetpack Compose and Stream Chat/Video SDK for Compose.
Kotlin
180
star
48

Flourish

๐ŸŽฉ Flourish implements dynamic ways to show up and dismiss layouts with animations.
Kotlin
174
star
49

compose-stable-marker

โœ’๏ธ Compose stable markers for KMP to tell stable/immutable guarantees to the compose compiler.
Kotlin
169
star
50

BaseRecyclerViewAdapter

โšก Fast way to bind RecyclerView adapter and ViewHolder for implementing clean sections.
Kotlin
163
star
51

Multi-ColorPicker

Android multi colorpicker for getting colors from any images by tapping on the desired color.
Kotlin
125
star
52

All-In-One

๐Ÿ‘” Health care application for reminding health-todo lists and making healthy habits every day.
Kotlin
118
star
53

Medal

๐Ÿ…An easy way to implement medal effect for Android.
Kotlin
111
star
54

viewmodel-lifecycle

๐ŸŒณ ViewModel Lifecycle allows you to track and observe Jetpack's ViewModel lifecycle changes.
Kotlin
104
star
55

WaterDrink

๐Ÿ’ง Simple water drinking reminder application based on MVP architecture.
Kotlin
75
star
56

CameleonLayout

A library that let you implement double-layer-layout changing with slide animation.
Kotlin
71
star
57

Awesome-Android-Persistence

A curated list of awesome android persistence libraries about SQLite, ORM, Mobile Database, SharedPreferences, etc.
70
star
58

SyncMarket

Let managing your application version update more simply.
Java
41
star
59

MagicLight-Controller

This simple demo application is controlling MagicLight's smart bulbs by bluetooth-le
Java
35
star
60

MethodScope

Reduce repetitive inheritance works in OOP world using @MethodScope.
Java
33
star
61

MapEditor

You can draw your map using by this Map Editor project.
C#
22
star
62

skydoves

๐Ÿ•Š skydoves
14
star
63

seungmani

This simple project is cocos-2dx c++ multi-patform(win32, android, ios, linux) game in Jan 2015.
C++
8
star
64

soniaOnline

XNA C# win 32/64 patform MMO game in Jan 2016.
C#
5
star
65

NityLife

This simple project is cocos-2dx c++ multi-patform(win32, android, ios, linux) game in 2014.
C++
5
star
66

Rurimo-Camera

You can take some screenshots or save images at clipboard so easily like just one click on Windows with this application.
C#
1
star