Skip to content
This repository was archived by the owner on Feb 26, 2023. It is now read-only.
This repository was archived by the owner on Feb 26, 2023. It is now read-only.

Common interface for SharedPreferences #1203

@chvndb

Description

@chvndb

Hi,

Is there a reason why the preference fields for shared preferences do not share a common interface that exposes the get and put methods? They all extend AbstractPrefField and all implement a get and put method, but it is not enforced.

However, (to clarify why I ask this question) I am trying to create a wrapper around these preference fields to make them observable (using rxjava). It is possible to make it work as follows:

import org.androidannotations.api.sharedpreferences.AbstractPrefField;
import rx.Observable;
import rx.subjects.BehaviorSubject;

public class PreferenceObservable<T> {

    private AbstractPrefField prefField;
    private BehaviorSubject<T> prefSubject;

    public PreferenceObservable(AbstractPrefField pref) {
        prefField = pref;
        prefSubject = BehaviorSubject.create(getLast());
    }

    public Observable<T> get() {
        return prefSubject.asObservable();
    }

    @SuppressWarnings("unchecked")
    public T getLast() {
        try {
            return (T) prefField.getClass().getMethod("get").invoke(prefField);
        } catch (Exception e) {}
        return null;
    }

    public void put(T value) {
        try {
            for (Method m : prefField.getClass().getMethods())
                if (m.getName().equals("put")) {
                    m.invoke(prefField, value);
                    prefSubject.onNext(value);
                    break;
                }
        } catch (Exception e) {}
    }
}

I am obliged to use reflection to get the methods I need. I know these methods are there, so I ignore error handling. Therefore, it would be better practice to simply expose these methods to avoid having to use this approach? Or maybe I am doing something wrong?

Cheers,

Christophe

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions