Giter VIP home page Giter VIP logo

prefser's Introduction

Prefser Android Arsenal

Wrapper for Android SharedPreferences with object serialization and RxJava Observables

min sdk version = 14

JavaDoc is available at: http://pwittchen.github.io/prefser/RxJava2.x

Current Branch Branch Artifact Id Build Status Coverage Maven Central
RxJava1.x prefser Build Status for RxJava1.x codecov Maven Central
☑️ RxJava2.x prefser-rx2 Build Status for RxJava2.x codecov Maven Central

This is RxJava2.x branch. To see documentation for RxJava1.x, switch to RxJava1.x branch.

Contents

Overview

Prefser wraps SharedPreferences and thanks to Java Generics provides you simpler API than classic SharedPreferences with the following methods:

<T> void put(String key, T value)
<T> T get(String key, Class<T> classOfT, T defaultValue)

We can also use TypeToken (e.g. for reading serialized Lists):

<T> T get(String key, TypeToken<T> typeTokenOfT, T defaultValue)

Prefser will serialize Lists correctly in put(...) method and will use TypeToken under the hood.

Classic SharedPreferences allows you to store only primitive data types, Strings and Set of Strings.

Thanks to Gson serialization, Prefser allows you to store:

  • Primitive data types
    • boolean
    • float
    • int
    • long
    • double
  • Strings
  • Custom Objects
  • Lists
  • Arrays
  • Sets

In addition, Prefser transforms OnSharedPreferenceChangeListener into Observable from RxJava:

Observable<String> observePreferences();

You can subscribe one of this Observable and monitor updates of SharedPreferences with powerful RxJava. You can also read data from RxJava Observables in order to monitor single shared preference with a specified key.

Creating Prefser object

You can create Prefser object in the following ways:

Prefser prefser = new Prefser(context);
Prefser prefser = new Prefser(sharedPreferences);

When you create Prefser object with Android Context, it will use default SharedPreferences from PreferenceManager.

You can set JsonConverter implementation for Prefser. When it's not set, Prefser will use GsonConverter by default.

Prefser prefser = new Prefser(context, jsonConverter);
Prefser prefser = new Prefser(sharedPreferences, jsonConverter);

Saving data

You can save data with the following method:

<T> void put(String key, T value)

Examples

prefser.put("key", true);               // put boolean
prefser.put("key", 43f);                // put float
prefser.put("key", 42);                 // put int
prefser.put("key", 42l);                // put long
prefser.put("key", 42.3);               // put double
prefser.put("key", "hello");            // put String
prefser.put("key", new CustomObject()); // put CustomObject

prefser.put("key", Arrays.asList(true, false, true));     // put list of booleans
prefser.put("key", Arrays.asList(1f, 2f, 3f));            // put list of floats
prefser.put("key", Arrays.asList(1, 2, 3));               // put list of integers
prefser.put("key", Arrays.asList(1l, 2l, 3l));            // put list of longs
prefser.put("key", Arrays.asList(1.2, 2.3, 3.4));         // put list of doubles
prefser.put("key", Arrays.asList("one", "two", "three")); // put list of Strings

List<CustomClass> objects = Arrays.asList(
  new CustomObject(),
  new CustomObject(),
  new CustomObject());

prefser.put(givenKey, objects); // put list of CustomObjects

prefser.put("key", new Boolean[]{true, false, true});     // put array of booleans
prefser.put("key", new Float[]{1f, 2f, 3f});              // put array of floats
prefser.put("key", new Integer[]{1, 2, 3});               // put array of integers
prefser.put("key", new Long[]{1l, 2l, 3l});               // put array of longs
prefser.put("key", new Double[]{1.2, 2.3, 3.4});          // put array of doubles
prefser.put("key", new String[]{"one", "two", "three"});  // put array of Strings

CustomObject[] objects = new CustomObject[]{
  new CustomObject(),
  new CustomObject(),
  new CustomObject()
};

prefser.put("key", objects); // put array of CustomObjects

Set<String> setOfStrings = new HashSet<>(Arrays.asList("one", "two", "three"));
Set<Double> setOfDoubles = new HashSet<>(Arrays.asList(1.2, 3.4, 5.6));
prefser.getPreferences().edit().putStringSet("key", setOfStrings).apply(); // put Set of Strings in a "classical way"
prefser.put("key", setOfDoubles); // put set of doubles

Reading data

get method

You can read data with the following method:

<T> T get(String key, Class<T> classOfT, T defaultValue)

or with TypeToken (e.g. when reading Lists):

<T> T get(String key, TypeToken<T> typeTokenOfT, T defaultValue)

Examples

// reading primitive types

Boolean value = prefser.get("key", Boolean.class, false);
Float value = prefser.get("key", Float.class, 1.0f);
Integer value = prefser.get("key", Integer.class, 1);
Long value = prefser.get("key", Long.class, 1.0l);
Double value = prefser.get("key", Double.class, 1.0);
String value = prefser.get("key", String.class, "default string");

// reading custom object

CustomObject value = prefser.get("key", CustomObject.class, new CustomObject());

// reading lists

// example with List of Booleans

List<Boolean> defaultBooleans = Arrays.asList(false, false, false);

TypeToken<List<Boolean>> typeToken = new TypeToken<List<Boolean>>() {
};

List<Boolean> readObject = prefser.get(givenKey, typeToken, defaultBooleans);

// in the same way we can read list of objects of any type including custom objects
// the only thing we need to do is replacing Boolean type with our desired type

// reading arrays

Boolean[] value = prefser.get("key", Boolean[].class, new Boolean[]{});
Float[] value = prefser.get("key", Float[].class, new Float[]{});
Integer[] value = prefser.get("key", Integer[].class, new Integer[]{});
Long[] value = prefser.get("key", Long[].class, new Long[]{});
Double[] value = prefser.get("key", Double[].class, new Double[]{});
String[] value = prefser.get("key", String[].class, new String[]{});
CustomObject[] value = prefser.get("key", CustomObject[].class, new CustomObject[]{});

// reading sets

Set<String> value = prefser.getPreferences().getStringSet("key", new HashSet<>()); // accessing set of strings in a "classical way"
Set<Double> value = prefser.get("key", Set.class, new HashSet<>());

observe method

You can observe changes of data with the following RxJava Observable:

<T> Observable<T> observe(String key, Class<T> classOfT, T defaultValue)

or with TypeToken (e.g when observing Lists):

<T> Observable<T> observe(String key, TypeToken<T> typeTokenOfT, T defaultValue)

Note

Use it, when you want to observe single preference under a specified key. When you want to observe many preferences, use observePreferences() method.

Example

Disposable subscription = prefser.observe(key, String.class, "default value")
  .subscribeOn(Schedulers.io())
  ... // you can do anything else, what is possible with RxJava
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Consumer<String>() {
    @Override public void accept(@NonNull String value) {
    // Perform any action you want.
    // E.g. display value in a TextView.
   }
});

getAndObserve method

You can combine functionality of get(...) and observe(...) methods with getAndObserve(...), which is defined as follows:

<T> Observable<T> getAndObserve(String key, Class<T> classOfT, T defaultValue)

or with TypeToken (e.g. when observing Lists):

<T> Observable<T> getAndObserve(String key, TypeToken<T> typeTokenOfT, T defaultValue)

You can subscribe this method in exactly the same way as observe(...) method. The only difference is the fact that this method will emit value from SharedPreferences as first element of the stream with get(...) method even if SharedPreferences were not changed. When SharedPreferences changes, subscriber will be notified about the change in the same way as in regular observe(...) method.

Contains method

You can check if data exists under a specified key in the following way:

prefser.contains("key");

Removing data

You can remove data under specified key in the following way:

prefser.remove("key");

When you want to clear all SharedPreferences you can use clear() method as follows:

prefser.clear();

Size of data

You can read number of all items stored in the SharedPreferences in the following way:

prefser.size();

Getting SharedPreferences object

You can get SharedPreferences object in the following way:

prefser.getPreferences();

You can use it for performing operations on SharedPreferences without Prefser library. E.g. for reading and writing Set of Strings, what is currently not supported by Prefser. See sections about saving data and reading data where you can find examples.

Subscribing for data updates

You can subscribe the following RxJava Observable from Prefser object:

Observable<String> observePreferences();

Note

Use it, when you want to observe many shared preferences. If you want to observe single preference under as specified key, use observe() method.

Example

Disposable subscription = prefser.observePreferences()
  .subscribeOn(Schedulers.io())
  .filter(...) // you can filter your updates by key
  ...          // you can do anything else, what is possible with RxJava
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Consumer<String>() {
    @Override public void accept(@NonNull String key) {
    // Perform any action you want.
    // E.g. get value stored under key
    // and display in a TextView.
  }
});

This subscription can be created e.g. in onResume() method, but it depends on your specific implementation and project requirements. Now, everytime when data in SharedPreferences changes, subscriber will be notified under which key value was updated and it can react on that change.

Unsubscribing from Observable

When you are subscribing for the updates in Activity, please remember to unsubscribe your subscriber in onPause() method in the following way:

@Override
protected void onPause() {
  super.onPause();
  subscription.dispose();
}

Examples

  • Examplary app using Prefser is available in the app directory.
  • If you want to use Prefser with PreferenceActivity, check out examplary in app-preference-activity directory.
  • More usage examples can be found in unit tests in PrefserTest class.

Download

If you want to use Observables, besides dependency to Prefser you should also add dependency to RxAndroid.

You can depend on the library through Maven:

<dependency>
    <groupId>com.github.pwittchen</groupId>
    <artifactId>prefser-rx2</artifactId>
    <version>x.y.z</version>
</dependency>
<dependency>
    <groupId>io.reactivex.rxjava2</groupId>
    <artifactId>rxandroid</artifactId>
    <version>2.1.1</version>
</dependency>

or through Gradle:

dependencies {
  compile 'com.github.pwittchen:prefser-rx2:x.y.z'
  compile 'io.reactivex.rxjava2:rxandroid:2.1.1'
}

Where x.y.z is the latest library release: Maven Central

Tests

Tests are available in library/src/test/java/ directory and can be executed via CLI with Robolectric with the following command:

./gradlew test

Code style

Code style used in the project is called SquareAndroid from Java Code Styles repository by Square available at: https://github.com/square/java-code-styles.

Static code analysis

Static code analysis runs Checkstyle, PMD and Lint. It can be executed with command:

./gradlew check

Reports from analysis are generated in library/build/reports/ directory.

Caveats

  • Set of Strings should be saved and read in a "classical way" with getPreferences() method.
  • TypeToken is required for proper Lists reading.
  • This library is just a wrapper around SharedPreferences, so it's not a database solution and it's not recommended to use it for large data sets, complicated data operations or adding new data frequently. For such use cases SQLite database or key-value database would be better choice.

Who is using this library?

  • Toss.im - a Korean app for consumer finance on mobile
  • and more...

Are you using this library in your app and want to be listed here? Send me a Pull Request or an e-mail to [email protected].

References

General information

Similar projects

License

Copyright 2015 Piotr Wittchen

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.

prefser's People

Contributors

danieldisu avatar dependabot-preview[bot] avatar plackemacher avatar pwittchen avatar semanticer avatar ubuntudroid avatar ypresto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prefser's Issues

Release 2.0.2

Initial release notes:

  • fixed bug reported in issue #70: get(...) method now returns a null value instead of "null" string when setting default value to null of String type
  • fixed RxJava usage in sample app
  • fixed RxJava usage in code snippets in README.md
  • changed code formatting to SquareAndroid
  • added static code analysis
  • improved code according to static code analysis suggestions

Things to do:

  • bump library version: PR #75
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Emit current value right on subscription to observable

When using this library, common use case is when I want to get the current value from prefser and populate my UI with it and then subscribe for change and update my UI again with any new value that comes from onNext. I don't know... maybe it would be better to emit current value right when I subscribe so we can skip the first step and get rid off the getter. Just fluently bind prefser to my views, using getter first seems too... imperative :)
I think this way, it would be more similar to approach of sqlbrite for example.

Provide convenience methods on top of get() for basic types

This looks a little bit noisy in my code

Boolean value = prefser.get("key", Boolean.class, false);
Float value = prefser.get("key", Float.class, 1.0f);
Integer value = prefser.get("key", Integer.class, 1);
Long value = prefser.get("key", Long.class, 1.0l);
Double value = prefser.get("key", Double.class, 1.0);
String value = prefser.get("key", String.class, "default string");

it would be nice to have a convenience methods like

Boolean value = prefser.getBoolean("key",  false);
Float value = prefser.getFloat("key", 1.0f);
Integer value = prefser.getInt("key", 1);
Long value = prefser.getLong("key", 1.0l);
Double value = prefser.getDouble("key", 1.0);
String value = prefser.getString("key", "default string");

And still use get() for custom objects.
It's also more similar to SharedPreferences approach.

Boolean default value returns a String

Hi,

Is there a reason why the default value of a Boolean does not return true or false but a String containing the value? In my opinion it must returns a boolean to avoid crashes.

Thanks

Release v. 2.0.1

Initial release notes:

  • bumped RxJava to v. 1.0.14
  • bumped Gradle Build Tools to v. 1.3.1

Possible missed update with getAndObserve()

This library uses Rx startWith() for observing and getting current value of share preferences.

.startWith(get(key, classOfT, defaultValue));

startWith(observe(), get()) (which is implemented as concat(get(), observe())) can miss update from shared preference change listener, because it only start observing after get() is completed.

ReactiveX/RxJava#3017 (comment)

It misses update when:

  1. Call getAndObserve()
  2. Observable of get() fetches value from shared preferences and stores it to local variable.
  3. Another thread updates preference value.
  4. Another thread notifies preference change, but Observable of observe() not subscribed yet.
  5. onNext() of get() is called with preference value fetched at 2.
  6. When Observable of get() is completed, then Observable of observe() is subscribed.
  7. Latest value of preference is set at 3, but this value will not be notified until next update!

Wrong return type when null is used for default value

We have just encountered a bug around type generics.

     public Observable<Boolean> observePreference() {
-        return mPrefser.getAndObserve(KEY, String.class, null); // emits String, but inferred as Observable<Boolean> by return type
+        return mPrefser.<String>getAndObserve(KEY, String.class, null)
+                .map(this::mapToBoolean);
     }

Second parameter of getAndObserve is raw type without type parameter: Class.
Class<T> should be used instead to make type inference work well.

But this causes unchecked assignment warnings when used with List.class, as type of List content is not specified.
Maybe related to issue about List type: #44.

More than 2 preferences observables

One of the problems I'm currently having it that Prefser stores only 1 onSharedPreferencesChangeListener. According to registerOnSharedPreferenceChangeListener when the reference is not stored somewhere, it will be garbage collected.

I'm trying to setup some observables throughout my app (currently 5 or so) and it is not really working. Do you have any advice about this?

Add more unit tests for observables

I've already added some unit tests for observables from primitive types.
Now, I need to add more tests for observables from a little bit more complicated data structures like custom objects, arrays, etc.

Release 2.0.4

Initial release notes:

  • bumped Gson dependency to v. 2.5
  • bumped RxJava dependency to v. 1.1.0
  • bumped Google Truth test dependency to v. 0.27

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Create release notes for 1.0.5

Done:

  • Removed final keyword from Prefser class in order to allow class mocking
  • Removed unused imports from Prefser class
  • Added test coverage report generation
  • Increased test coverage to 100%
  • Added abstraction for JsonConverter and default GsonConverter
  • Added getAndObserve(...) method
  • Emitting current value right on subscription to Observable with getAndObserve(...) method

Release 2.0.3

Initial release notes:

  • added @NonNull Android support annotations
  • updated Gson dependency to the newest version
  • updated Target Android SDK version to 23
  • removed Dagger 1 sample app, because it was outdated and too trivial

Things to do:

  • bump library version ➡️ PR #79
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Update naming convention in the API

  • from(...) should be changed to observe(preferences)
  • fromDefaultPreferences() should be changed to observeDefaultPreferences()
  • getObservable(...) should be changed to observe(key, type, defaultValue)
  • methods responsible for reading data without setting default values should be removed

Create a fromJson method that accepts a Type

Gson can convert from a TypeToken, and sometimes that is desirable. One thing that I'm having trouble is that I need a List and Gson is returning me a List. I can't pass a List.class because it does not exists, and I can't pass a Type too because the interface don't have this method.

The way I'm trying to do and the return value is wrong:

List<Account> accounts = prefser.get(Constants.PreferencesKeys.ACCOUNTS, List.class, new ArrayList<>())

Add abstraction for JSON converter

Create default GsonConverter and add possibility to implement another JSON converter (with fromJson(jsonString) and toJson(object) methods).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.