A easy way to use android sharepreference

Overview

Favor

Build Status Android Arsenal

A easy way of using Android SharedPreferences.

How to use this library

  • Using Gradle
    compile 'com.cocosw:favor:0.2.0@aar'
  • Using Maven
<dependency>
    <groupId>com.cocosw</groupId>
    <artifactId>favor</artifactId>
    <version>0.2.0</version>
    <type>apklib</type>
</dependency>

API

1 Define a interface.

@AllFavor
public interface Account {
    @Default("No Name")
    String getUserName();
    String setPassword(String password);
}

2 The FavorAdapter class generates an implementation of the interface.

account = new FavorAdapter.Builder(getContext()).build().create(Account.class);
account.setPassword("Passw0rd");
String username = account.getUserName();

API Declaration

@AllFavor

@AllFavor
public interface Account {
    @Default("No Name")
    String getUserName();
    String getPassword();
}

@Favor

    @Favor("city")
    @Default("Sydney")
    String city();

equals

    PreferenceManager.getDefaultSharedPreferences(context).getString("city","Sydney");

And you can simplify it, Favor will extract the key from the method name

    @Favor
    @Default("Sydney")
    String city();

@Default

    @Default("18")
    int age();
    
    @Default("true")
    boolean alive();

@Commit

By default, Favor will call editor.apply() (>api9), but you can force it to use editor.commit() by @Commit

    @Favor
    @Commit
    void setAddress(String address);

RxPreference

You are a RxJava fan, easy! (rx-preferences dependency is required)

    @Favor
    @Default("No Name")
    Preference<String> name();

Advanced usage

Favor support put/get all primitive types, including int/long/float/String/bool, String set is also supported for API>=11. From 0.2.0, Favor (Experimentally) supports Serializable object saving/loading.

    public class Image implements Serializable {
    ....
    }
   
    @Favor
    Image image();

    @Favor
    void setImage(Image image);

There is one limitation that you can't set default value for Serializable preference item.

Proguard

# Favor
-dontwarn com.cocosw.favor.** { *; }
-keep class com.cocosw.favor.** { *; }

Contribute

  • Feel free to send your pull request to me.

License

Copyright 2011, 2015 Kai Liao

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.
Comments
  • Unit tests to raise the code coverage by 18%

    Unit tests to raise the code coverage by 18%

    Hi Kai @soarcn

    This pull request is a sample of unit test cases that we plan to contribute in order to raise the overall coverage to 80%. Code coverage is measured using Android Studio. This pull request increases code coverage of library from 0% to 18%.

    | Metric | Before | After | | --- | --- | --- | | Coverage % | 0% | 18% | | Lines Covered | 0 | 80 | | Total Lines | 440 | 440 |

    Please let me know if you have any questions.

    Mohd Farid DevFactory - Code Quality Team

    opened by mfarid 5
  • [enhancement] add a way to specify the preferences file name

    [enhancement] add a way to specify the preferences file name

    When using [getSharedPreferences(java.lang.String, int)](https://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String, int%29) instead of getDefaultSharedPreferences(android.content.Context), you have to specify the preferences file name. It would be nice to have a way to specify that file name to Favor so that getSharedPreferences(java.lang.String, int) would be called using it. The idea is to keep the old preferences when migrating to Favor in an application that was already using getSharedPreferences(java.lang.String, int) without losing the current preferences or having to do a migration.

    opened by 0xjohnnycage 3
  • Enhancement: Support Serializable for rxPreferences

    Enhancement: Support Serializable for rxPreferences

    I wanted to use Serializable with rxPreferences as such:

    @AllFavor
    public interface MapPreference {
        Preference<BaseTileType> baseTile();
    }
    

    With BaseTileType implementing Serializable interface. However, I saw that Favor doesn't handle rxPreference serializable data.

    I tested the following changes, which seem to work:

    MethodInfo.java

        // Adding serializable adapter to be used with rxPreferences
        class SerializableAdapter<T extends Serializable> implements Preference.Adapter<T> {
    
            @Override
            public T get(@NonNull String key, @NonNull SharedPreferences preferences) {
                String gets = preferences.getString(key, null);
                if (TextUtils.isEmpty(gets))
                    return null;
                byte[] bytes = Base64.decode(gets, Base64.DEFAULT);
                return (T)Taste.SerializableTaste.deserialize(bytes);
            }
    
            @Override
            public void set(@NonNull String key, @NonNull T value, @NonNull SharedPreferences.Editor editor) {
                byte[] bytes = Taste.SerializableTaste.serialize(value);
                if (bytes != null) {
                    editor.putString(key, Base64.encodeToString(bytes, Base64.DEFAULT));
                }
            }
        }
    
        // Handle Serializable for rxPreference
        private void parseMethodAnnotations() {
            ...
            } else if (responseObjectType == Boolean.class) {
                    rxPref = rx.getBoolean(key, defaultValues[0] == null ? null : Boolean.valueOf(defaultValues[0]));
                } else if (Serializable.class.isAssignableFrom(Types.getRawType(responseObjectType))) {
                    SerializableAdapter adapter = new SerializableAdapter();
                    rxPref = rx.getObject(key, defaultValues[0] == null ? null : Taste.SerializableTaste.deserialize(defaultValues[0].getBytes()), adapter);
            } else {
            ...
        }
    

    This seems to work well and I was able to use it. Can you look over it? I can make a PR or, if you can, you can apply the changes. What do you think?

    opened by dragantl 2
  • Read variable in @Default

    Read variable in @Default

    Hi! First of all, thank you for this lib. I have a simple question. Is it possible to read some variable in @Default annotation, maybe something like this:

    @Default("GoogleMap.MAP_TYPE_NORMAL")

    Thanks in advance for you reply.

    opened by stanmots 1
  • minifyEnabled gives java.lang.ClassCastException

    minifyEnabled gives java.lang.ClassCastException

    This looks to be similar to #4. However, because there wasn't a clear solution identified, I wanted to create a separate issue.

    I'm using Favor along with RxPreference. The application builds fine with minifyEnabled set to true. However, when it runs, I get the following exception:

    Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
       at com.cocosw.favor.MethodInfo.parseResponseType(Unknown Source)
       at com.cocosw.favor.MethodInfo.<init>(Unknown Source)
       at com.cocosw.favor.FavorAdapter.getMethodInfo(Unknown Source)
       at com.cocosw.favor.FavorAdapter.access$400(Unknown Source)
       at com.cocosw.favor.FavorAdapter$FavorHandler.invoke(Unknown Source)
       at java.lang.reflect.Proxy.invoke(Proxy.java:393)
       at $Proxy1.a(Unknown Source)
       at com.teralogics.test.TestApplication.onCreate(Unknown Source)
       at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1013)
       at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4707)
       at android.app.ActivityThread.-wrap1(ActivityThread.java) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:148) 
       at android.app.ActivityThread.main(ActivityThread.java:5417) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    

    Within the TestApplication.onCreate, I do the following:

    @Override
    public void onCreate() {
        sApplication = this;
    
        super.onCreate();
    
        DevicePreference devicePreference = new FavorAdapter.Builder(this).build().create(DevicePreference.class);
    
        if (!devicePreference.uid().isSet()) {
            devicePreference.uid().set(UUID.randomUUID().toString());
        }
    }
    

    Definition of device preference is as follows:

    @AllFavor
    public interface DevicePreference {
        Preference<String> uid();
    }
    

    My ProGuard has the following entry (notice, I removed { *; } as it is not a valid -dontwarn syntax)

    # Favor
    -dontwarn com.cocosw.favor.**
    -keep class com.cocosw.favor.** { *; }
    

    The app runs fine in a non-minified debug build.

    opened by dragantl 1
  • java.lang.ClassCastException

    java.lang.ClassCastException

    Got: @Commit @Default("-1") void setProjectId(int project); int getProjectId();

    and now this: int selected = getSettings().getProjectId();

    equals to Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)

    opened by krzysiek-zgondek 1
  • add proguard configure

    add proguard configure

    Warning:com.cocosw.favor.MethodInfo: can't find referenced class com.f2prateek.rx.preferences.RxSharedPreferences
    Warning:com.cocosw.favor.MethodInfo: can't find referenced class com.f2prateek.rx.preferences.Preference
    Warning:com.cocosw.favor.MethodInfo: can't find referenced class com.f2prateek.rx.preferences.RxSharedPreferences
    Warning:there were 10 unresolved references to classes or interfaces.
             You may need to add missing library jars or update their versions.
             If your code works fine without the missing classes, you can suppress
             the warnings with '-dontwarn' options.
             (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
    Exception while processing task 
    java.io.IOException: Please correct the above warnings first.
    

    my proguard.txt (it's working)

    # favor
    -dontwarn com.cocosw.favor.** { *; }
    -keep class com.cocosw.favor.** { *; }
    
    opened by captain-miao 1
  • renaming method to fix typing error

    renaming method to fix typing error

    Hello, I really wanna help to improve your library.

    I have just a small contribution by now but I wanna help you as much as I can. How should I proceed? Should I open some issues about features that I think that makes sense? Or just implement then and submit for your review?

    Best regards.

    opened by rodrigohenriques 1
  • Please update Proguard section

    Please update Proguard section

    I got some problem with Proguard.

    Information from Readme is not correct for 1st line,

    -dontwarn com.cocosw.favor.** { ; } -keep class com.cocosw.favor.* { *; }

    Also preferences was not create and stored until I have added information about to keep my interface with @Flavor too

    -dontwarn com.cocosw.favor.** 
    -keep class com.cocosw.favor.** { *; }
    -keep interface {your.package}.{YourInterface} {
      <methods>;
    }
    
    
    opened by igozhenko 0
  • Fixing squid: S1192 String literals should not be duplicated

    Fixing squid: S1192 String literals should not be duplicated

    This pull request is focused on resolving occurrences of Sonar rule squid:S1192 - “String literals should not be duplicated”. This PR will remove 70min of TD. You can find more information about the issue here: https://dev.eclipse.org/sonar/rules/show/squid:S1192 Please let me know if you have any questions. Fevzi Ozgul

    opened by devFozgul 2
Android Parcelable models made easy

AutoParcel AutoParcel is an AutoValue extension that enables Parcelable values generation. Just add implements Parcelable to your @AutoValue annotated

Francesco Sardo 1.4k Dec 23, 2022
A tool to generate Android ContentProviders.

Android ContentProvider Generator (acpg) A tool to generate Android ContentProviders. It takes a set of entity (a.k.a "table") definitions as the inpu

Benoit Lubek 623 Dec 13, 2022
A custom view styling library for Android that generates the obtainStyledAttributes() and TypedArray boilerplate code for you.

DEPRECATED This project is no longer maintained. Consider using https://github.com/airbnb/paris Barber Barber is your personal custom view stylist. Si

Zac Sweers 716 Dec 30, 2022
A code generator to create Android ContentProvider

DatabaseCodeGenerator This project is a code generator written in Java used to generate Android code. Given a database schema JSON definition file, it

Foxykeep 297 Nov 25, 2022
Pure Java code generation tool for generating a fully functional ContentProvider for Android.

RoboCoP RoboCoP is a Java library that can generate a fully-functional ContentProvider from a simple JSON schema file. Get the latest version from our

Rain 246 Dec 29, 2022
Codegeneration tool for isomorphic server and mobile Go apps with gRPC & Protobuf. Share code between your backend, Android & iOS app! :sun_with_face:

Anakin Codegeneration tool for isomorphic server and mobile Go apps with gRPC & Protobuf. Share code between your backend, Android & iOS app! Descript

Kirill Biakov 17 Jun 25, 2020
Android 注解自动生成与 Flutter 通信的代码

Android-Flutter-Annotation 用于 Android 端项目,通过使用注解自动生成与 Flutter 通信的代码。 可生成的三种通信渠道有: MethodChannel EventChannel BasicMessageChannel 集成 在项目的 build.gradle

JOYY UED 4 Nov 1, 2021
A small tool to help you generate android projects that have a base code.

Volt Project A small tool to help you generate android projects that have a base code. Usage Change project in base directory. python volt-gen.py <pac

Victor Varenik 3 Feb 2, 2022
An easy way to customize your log in Android,including output to console, writing log to file in high performance way and so on

EasyLog An easy way to customize your log in Android,including output to console, writing log to file in high performance way and so on. 1. Initializa

Taylor 40 Dec 8, 2022
The easy way to use biometric authentication in your Flutter app. Supports Fingerprint, FaceID and Iris.

BiometricX The easy way to use biometric authentication in your Flutter app. Supports Fingerprint, FaceID and Iris. Demo APK. Starting $ flutter pub a

Salman S 13 Dec 15, 2022
A general purpose kotlin library that use kotlin coroutines, flows and channels to provide timer features with the most easy and efficient way

Timer Timer is a general purpose kotlin library that use kotlin coroutines, flows and channels to provide timer features with the most easy and effici

Amr Saraya 3 Jul 11, 2022
kinstall is an easy way to install gradle-based command-line kotlin projects that use the application plugin.

kinstall kinstall is an easy way to install gradle-based command-line kotlin projects that use the application plugin. use First, install kinstall its

david kilmer 0 Apr 24, 2022
[Development stopped in 2014. Unfinished and not stable - not recommended to use.] An easy-to-use ViewPager subclass with parallax background effect for Android apps.

Development stopped in 2014 Not developed since 2014. Unfinished and not stable - not recommended to use. ParallaxViewPager An easy-to-use ViewPager s

Andras Kindler 437 Dec 29, 2022
TourGuide is an Android library that aims to provide an easy way to add pointers with animations over a desired Android View

TourGuide TourGuide is an Android library. It lets you add pointer, overlay and tooltip easily, guiding users on how to use your app. Refer to the exa

Tan Jun Rong 2.6k Jan 5, 2023
Simple Android Library, that provides easy way to start the Activities with arguments.

Warning: Library is not maintained anymore. If you want to take care of this library, propose it via Pull Request. It needs adjustmensts for newer ver

Marcin Moskała 429 Dec 15, 2022
Insanely easy way to work with Android Database.

Sugar ORM Insanely easy way to work with Android databases. Official documentation can be found here - Check some examples below. The example applicat

null 2.6k Dec 16, 2022
Android library to achieve in an easy way, the behaviour of the home page in the Expedia app, with a pair of auto-scroll circular parallax ListViews.

ListBuddies This library is not maintained anymore and there will be no further releases Android library of a pair of auto-scroll circular parallax Li

JPARDOGO 970 Dec 29, 2022
An easy, flexible way to add a shimmering effect to any view in an Android app.

Shimmer for Android Shimmer is an Android library that provides an easy way to add a shimmer effect to any view in your Android app. It is useful as a

Facebook 5.1k Dec 31, 2022
:sparkles: An easy way to implement an elastic touch effect for Android.

ElasticViews ✨ An easy way to implement an elastic touch effect for Android. Including in your project Gradle Add below codes to your root build.gradl

Jaewoong Eum 763 Dec 29, 2022
An easy, flexible way to add a shimmering effect to any view in an Android app.

Shimmer for Android Shimmer is an Android library that provides an easy way to add a shimmer effect to any view in your Android app. It is useful as a

Facebook 5.1k Dec 26, 2022