百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

PreferenceRoom

> 编程语言
开源

:truck:用于高效地和从结构上管理"共享优先"持久性的Android处理库.

378 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

:truck:用于高效地和从结构上管理"共享优先"持久性的Android处理库.

PreferenceRoom

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 | :---------------: | :---------------: | :---------------: | :---------------: | :---------------: | | | | | |

Download

Gradle

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

gradle
allprojects {
    repositories {
        mavenCentral()
    }
}

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

gradle
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

  • KeyName
  • TypeConverter
  • PreferenceFunction
  • EncryptEntity

2.PreferenceComponent

3.Dependency Injection (Use with dagger)

4.Usage in Kotlin (Incremental annotation processing)

5.Proguard-Rules

6.Debugging with Stetho

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.

…

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

…

we can listen the changed value using OnChangedListener.

onChanged method will be invoked if we change the value using put method.

java
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.

java
@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.

java
PreferenceManager.getDefaultSharedPreferences(context);

So we can connect with PreferenceFragmentCompat, PreferenceScreen or etc.

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.

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

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.

java
@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.

java
public class PetConverter extends PreferenceTypeConverter {

    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.

java
public class BaseGsonConverter extends PreferenceTypeConverter {

    private final Gson gson;

    public BaseGsonConverter(Class 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.

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

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

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.

java
@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.

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

Or we can customize encrypting and decrypting algorithm using PreferenceFunction.

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

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

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.

java
@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.

java
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.

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

Dependency Injection

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.

java
@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.

java
@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.

java
@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.

java
@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.

java
@PreferenceComponent(entities = [Profile::class, Device::class])
interface UserProfileCompo

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Javaandroidandroid-libraryannotation-processingannotation-processor

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言