[JAVA] Created a library that makes it easy to handle Android Shared Prefences

I secretly made a library that makes it easy to handle Android's Shared Prefences, so I will take advantage of the Advent calendar and introduce it.

Preferhythm

https://github.com/KazaKago/Preferhythm DownloadBuildStatuslicense

What's this?

When developing an Android app, you may save the value on your device, but in that case you usually use Shared Preferences. However, I personally thought that it would be difficult to use or that it would be a hotbed for human error such as typo, so I made a wrapper library for Shared Preferences with the spirit that I should make it. I think that there are many people who write standard code like ↓, so I use automatic code generation by Annotation Processor to simplify it.

class MyPreferences(context: Context) {

    private val preferences = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE)
    private val tokenKey = "session_token"

    fun getToken(): String? {
        return preferences.getString(tokenKey, null))
    }

    fun setToken(value: String?) {
        val editor = preferences.edit()
        editor.putString(tokenKey, value)
        editor.apply()
    }

}

If you use this library, the above code will be ↓.

@PrefClass
class MyPreferences {

    @PrefField
    val token: String?
}

This may free you from the "syndrome that you can't help but worry about missing changes even though you have copied and pasted" when the value to be saved increases.

Requirement

--Android 4.0.3 (API 15) or above

Install

Please add the following to gradle.build of the module to be used. For Kotlin, don't forget ʻapply plugin:'kotlin-kapt'`.

Java

dependencies {
    implementation 'com.kazakago.preferhythm:preferhythm:x.x.x'
    annotationProcessor 'com.kazakago.preferhythm:preferhythm-processor:x.x.x'
}

Kotlin

apply plugin: 'kotlin-kapt'

dependencies {
    implementation 'com.kazakago.preferhythm:preferhythm:x.x.x'
    kapt 'com.kazakago.preferhythm:preferhythm-processor:x.x.x'
}

Click here for Latest Version → [Download](https://bintray.com/kazakago/maven/preferhythm/ _latestVersion)

Usage

Add @PrefClass annotation to the class you want to model in Preferences, Attach the @PrefField annotation to the field variable you want to save and the model setting is complete.

@PrefClass //In the model class for SharedPreferences@Please attach PrefClass
class MyPreferences {

    @PrefField //For each value you want to save@Please attach PrefField
    int intValue = 3; //The default value when there is no value is 3

    @PrefField
    boolean booleanValue; //The default value when there is no value is false, which is the same as the default of boolean type.

    @PrefField
    String stringValue; //The default value when there is no value is null

    @NonNull
    @PrefField
    String nonNullStringValue = "foo"; //The default value when there is no value"foo".. Also@It is possible to reflect it in the method generated by adding NonNull annotation.

}

If you build in the above state, a class named "model class name with @ PrefClass + Manager "will be automatically generated. A setter getter is automatically implemented for each field with @ PrefField, so if you set it in that method and apply (), it will be saved. only this!

public class MainActivity extends Activity {

    // `MyPreferencesManager`Is automatically generated
    private MyPreferencesManager myPreferencesManager = new MyPreferencesManager(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        System.out.print(myPreferencesManager.getIntValue()); // 3 (Default value)

        myPreferencesManager.setIntValue(100); //Set 100
        myPreferencesManager.commit(); //To reflect the changes, call commit or apply as in Shared Preferences.

        System.out.print(myPreferencesManager.getIntValue()); //It will be 100 set
        
        myPreferencesManager.clear(); //Clear the values contained in MyPreferencesManager
        myPreferencesManager.commit();

        System.out.print(myPreferencesManager.getIntValue()); // 3 (Will be the default value again)
    }

}

Works with Java and Kotlin in the repository Please see that as it contains a sample to

Important

Preferences name

By default, the Shared Preferences name reflects the class name If this is inconvenient, you can change it freely by tweaking the annotation parameters.

@PrefClass("YOUR_ORIGINAL_PREFERENCES_NAME")
class YourPreferencesClass {

...

}

Key name

Similarly, the field variable name is reflected by default in the key name when saving to Shared Preferences. This can also be changed by inserting an arbitrary character string into the annotation parameter.

@PrefClass
class YourPreferencesClass {

    @PrefField("YOUR_ORIGINAL_KEY_NAME")
    int yourSaveValue;

}

Use this option if you want to take over the already implemented SharedPreferecne or key.

Advanced

Getter, Setter method override

Since the automatically generated "model class name with @ PrefClass + Manager "class can be inherited, it is possible to interrupt arbitrary processing by overriding the method.

public class CustomMyPreferencesManager extends MyPreferencesManager {

    public CustomMyPreferencesManager(@NonNull Context context) {
        super(context);
    }
    
    @Nullable
    @Override
    public String getStringValue() {
        //Please do something if necessary
        // ex)Decryption
        return super.getStringValue();
    }

    @NonNull
    @Override
    public MyPreferencesManager setStringValue(@Nullable String value) {
        //Please do something if necessary
        // ex)Encryption
        return super.setStringValue(value);
    }

}

Kotlin Support

This library is also assumed to be used from Kotlin, and code that considers Nullable and NonNull syntax is generated.

@PrefClass
class MyPreferences {

    @PrefField
    val intValue: Int = 3 //NonNull and default value is 3

    @PrefField
    val booleanValue: Boolean = false //NonNull and default value is false

    @PrefField
    val stringValue: String = "foo" //NonNull and the default value is`foo`

    @PrefField
    val nullableStringValue: String? = null //Nullable and default value is null

    @PrefField
    val nullableStringWithInitValue: String? = "bar" //Nullable and the default value is"bar"

}

Supported Type

The types supported by this library are as follows Since it is a Wrapper Library for Shared Preferences, the supported types are the same. See Official Documentation for more information.

License

Distributed under the MIT license

Recommended Posts

Created a library that makes it easy to handle Android Shared Prefences
LazyBLE Wrapper (created a library that makes Android BLE super simple) v0.14
Created a multifunctional routing library for Android that also supports Shared Element --MoriRouter
A solution that makes it easy to input Procon and Web tests to verify results
[Node.js] Docker-compose up makes it easy to build a development environment
I made a GitHub Action that makes it easy to understand the execution result of RSpec
Think of RxJava as a library that makes asynchronous processing easier to write
A memo that was soberly addicted to the request of multipart / form-data
Created a library that makes it easy to handle Android Shared Prefences
It was surprisingly easy. How to update user information without entering a password
A story that made it as easy as possible to check the operation when automatically creating a library update PR with Github Dependabot
The story of making a binding for libui, a GUI library for Ruby that is easy to install
A story that made it convenient with Kotlin that it is troublesome to execute animation continuously on Android
Easy to create Processing library
[Ruby 3.0] A memo that I added a type definition to a library I wrote
How to identify the path that is easy to make a mistake
Let's write a code that is easy to maintain (Part 2) Name