• Stars
    star
    228
  • Rank 175,267 (Top 4 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

Wrapper for Android SharedPreferences with object serialization and RxJava Observables

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.

More Repositories

1

ReactiveNetwork

Android library listening network connection state and Internet connectivity with RxJava Observables
Java
2,527
star
2

spotify-cli-linux

🎢 A command line interface to Spotify on Linux
Python
637
star
3

NetworkEvents

Android library listening network connection state and change of the WiFi signal strength with event bus
Java
449
star
4

swipe

πŸ‘‰ detects swipe events on Android
Java
328
star
5

RxBiometric

☝️ RxJava and RxKotlin bindings for Biometric Prompt (Fingerprint Scanner) on Android
Kotlin
301
star
6

WeatherIconView

Weather Icon View for Android applications
Java
204
star
7

ReactiveWiFi

Android library listening available WiFi Access Points and related information with RxJava Observables
Java
189
star
8

InfiniteScroll

Infinite Scroll (Endless Scrolling) for RecyclerView in Android
Java
189
star
9

ReactiveBeacons

Android library scanning BLE beacons nearby with RxJava
Java
167
star
10

ReactiveSensors

Android library monitoring device hardware sensors with RxJava
Java
166
star
11

learning-linux

learning Linux (Unix) and collecting resources about it
99
star
12

kirai

String formatting library for Java, Android, Web and Unix Terminal
Java
71
star
13

interview-questions

interview questions for the software developer role and related resources
69
star
14

RxBattery

monitors battery state of the Android device
Kotlin
63
star
15

tmux-plugin-spotify

tmux plugin displaying currently played song on Spotify (linux only)
Shell
53
star
16

neurosky-android-sdk

Android SDK for the NeuroSky MindWave Mobile Brainwave Sensing Headset
Java
47
star
17

EEGReader

EEG Reader is an Android mobile application, which reads EEG signal from NeuroSky mobile device connected to smartphone via Bluetooth.
Java
39
star
18

android-quality-starter

setup CheckStyle, FindBugs, PMD and Lint for your Android project easily
Shell
29
star
19

ydocker

[unofficial PoC] get, build, initialize and run SAP Hybris Commerce Suite inside Docker container
Shell
29
star
20

ReactiveBus

🚍 Reactive Event Bus for JVM (1.7+) and Android apps built with RxJava 2
Java
17
star
21

android-looper-sample

Exemplary Android app showing usage of Handler and Looper
Java
15
star
22

SearchTwitter

Android app, which allows to search tweets as user types and scroll them infinitely (Contentful Android Task)
Java
15
star
23

learn-python-the-hard-way

Set of programs written during learning basics of Python and related resources 🐍
Python
13
star
24

dockerfiles-java

various docker images with java
Dockerfile
11
star
25

dotfiles

my dotfiles
Shell
10
star
26

dockerw

docker wrapper bash script template
Shell
10
star
27

android-resource-converter

Scripts converting Android *.xml resources with translations to *.csv file and backwards
Python
9
star
28

ReactiveAirplaneMode

✈️ Android library listening airplane mode with RxJava Observables
Java
8
star
29

money-transfer-api

HTTP server with REST API for money transfer between bank accounts (Revolut Backend Task)
Java
8
star
30

pkup

semi-automated generating of PKUP report
Python
6
star
31

airly-statusbar

bash script for reading AQI from the airly.eu sensors for BitBar (macOS) and Argos (Linux + Gnome) statusbar
Shell
6
star
32

learning-csharp

Set of simple programs written during learning basics of C# language
C#
4
star
33

fix-skype-icon

☎️ shell script to fix the Skype icon in Ubuntu
Shell
4
star
34

tmux-plugin-ip

tmux plugin showing IP number
Shell
4
star
35

voucher-storage-service

microservice developed during "Kyma meets CCV2 Hackathon"
Kotlin
4
star
36

reactive-client-server

An example of reactive client and server apps written for "Hack Your Career" presentation about Reactive Programming at Silesian University of Technology
Java
4
star
37

touch

Android library, which allows to monitor raw touch events on the screen of the device with RxJava
Java
3
star
38

wittchen.io

a source code of my personal website and blog
HTML
3
star
39

learning-cobol

Repository created to learn basics of COBOL language and feel some vintage breeze
COBOL
3
star
40

ydownloader

shell script for downloading SAP Hybris Commerce Suite from Artifactory
Shell
3
star
41

tmux-auto-pane

a tiny tool for creating pre-defined tile layouts in tmux on linux with xdotool
Shell
3
star
42

learning-R

Repository created in order to learn basics of R language
R
2
star
43

serverless-lambda-playground

Playing around with serverless solutions, lambdas, cloud functions, etc.
Java
2
star
44

noti.py

simple script to show system notifications on Linux
Python
2
star
45

git-branch-comparator

Checks if development branch has all changes from master branch in Git repository
Python
2
star
46

HriseyPlayground

Playing with Hrisey to remove boilerplate code from Android projects
Java
2
star
47

java-flow-experiments

Experimenting with Reactive Streams in Java 8 and Java 9. This repository is prepared for my talk "Get ready for java.util.concurrent.Flow!" at JDD 2017 Conference in KrakΓ³w, Poland
Java
2
star
48

wallpapers

wallpapers I use on my desktop
1
star
49

learning-go

learning basics of go language
Go
1
star
50

craplog

verifies whether your git log is a crap or not
Python
1
star
51

nyan-cat-loader

Nyan cat loader made just for fun in HTML5, CSS3 and JavaScript.
CSS
1
star
52

learning-asm-x64-linux

Repository created in order to learn basics of Assembly x64 for Linux
Assembly
1
star
53

tmux-plugin-uptime

tmux plugin showing computer uptime
Shell
1
star
54

java-playground

a repo created for testing and learning different features of java and jvm libraries
Java
1
star
55

cv

my cv/resume as a code in LaTeX
TeX
1
star
56

tmux-plugin-ram

tmux plugin showing RAM usage
Shell
1
star
57

tmux-plugin-battery

tmux plugin showing battery level
Shell
1
star
58

github-actions-playground

a repo for testing GitHub Actions
1
star
59

HelloAndroidKotlin

Hello World Android app written in Kotlin
Kotlin
1
star
60

learning-docker

learning basics of Docker
Makefile
1
star
61

yaas-java-sdk

YaaS (Hybris as a Service) Java SDK
Java
1
star
62

Ant-algorithm

Implementation of the ant algorithm for AI laboratory at my univeristy.
Pascal
1
star
63

kotlin-playground

Repository created in order to learn basics of Kotlin language
Kotlin
1
star