Skip to content

Persist with SharedPreferences

xcesco edited this page Dec 28, 2020 · 7 revisions

To persist beans with SharedPreference, we need to define the class that contains properties that SharedPreference will persist.

Kritpon uses an annotation processor to generate boilerplate code necessary to interact with shared preferences.

Kripton initialization

Before use Kripton to persit on shared preferences, an Android app have to initialize Kripton library. To do this, just add the following code to Application class (tipically on method onCreate):

// set context for Kripton Library
KriptonLibrary.init(this);

Usage

Consider the follow bean definition:

@BindType
public class User  {
    public long id;
    public String email;
    public String name;
    public String surname;
    public String username;
}

A share preferences definition can be done with a simple class:

@BindSharedPreferences
public class SecurityPreferences {
  public User user;
}

The Kripton Annotation Processor will generate for us BindSecurityPreferences to work with shared preferences. In this way, after run the annotation processor, to work with shared preferences we will write:

final User bean=new User();
...
BindSecurityPreferences security=BindSecurityPreferences.getInstance();
security.edit().putUser(bean).commit();	

There some feature of generated shared preference that we want to underline:

  • BindSecurityPreferences derives from Shared Preference, so it inherit all its method and its "way of working".
  • BindSecurityPreferences is a singleton.
  • BindSecurityPreferences contains a Editor specialized to work with SecurityPreferences fields.

The generated class is:

/**
 * This class is the shared preference binder defined for SecuritySharedPreferences
 *
 * @see SecuritySharedPreferences
 */
public class BindSecuritySharedPreferences extends AbstractSharedPreference {
  /**
   * instance of shared preferences
   */
  private static BindSecuritySharedPreferences instance;

  /**
   * working instance of bean
   */
  private final SecuritySharedPreferences defaultBean;

  /**
   * PersonBindMap */
  private PersonBindMap personBindMap = AbstractContext.mapperFor(Person.class);

  /**
   * constructor
   */
  private BindSecuritySharedPreferences() {
    // no name specified, using default shared preferences
    prefs=PreferenceManager.getDefaultSharedPreferences(KriptonLibrary.context());
    defaultBean=new SecuritySharedPreferences();
  }

  /**
   * create an editor to modify shared preferences
   */
  public BindEditor edit() {
    return new BindEditor();
  }

  /**
   * reset shared preferences
   */
  public void reset() {
    SecuritySharedPreferences bean=new SecuritySharedPreferences();
    write(bean);
  }

  /**
   * read bean entirely
   *
   * @return read bean
   */
  public SecuritySharedPreferences read() {
    SecuritySharedPreferences bean=new SecuritySharedPreferences();
     {
      String temp=prefs.getString("person", null);
      bean.person=StringUtils.hasText(temp) ? parsePerson(temp): null;
    }


    return bean;
  }

  /**
   * write bean entirely
   *
   * @param bean bean to entirely write
   */
  public void write(SecuritySharedPreferences bean) {
    SharedPreferences.Editor editor=prefs.edit();
    if (bean.person!=null)  {
      String temp=serializePerson(bean.person);
      editor.putString("person",temp);
    }  else  {
      editor.remove("person");
    }


    editor.commit();
  }

  /**
   * read property person
   *
   * @return property person value
   */
  public Person person() {
    String temp=prefs.getString("person", null);
    return StringUtils.hasText(temp) ? parsePerson(temp): null;

  }

  /**
   * write
   */
  protected String serializePerson(Person value) {
    if (value==null) {
      return null;
    }
    KriptonJsonContext context=KriptonBinder.jsonBind();
    try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
      JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
      int fieldCount=0;
      if (value!=null)  {
        fieldCount++;
        personBindMap.serializeOnJackson(value, jacksonSerializer);
      }
      jacksonSerializer.flush();
      return stream.toString();
    } catch(Exception e) {
      throw(new KriptonRuntimeException(e.getMessage()));
    }
  }

  /**
   * parse
   */
  protected Person parsePerson(String input) {
    if (input==null) {
      return null;
    }
    KriptonJsonContext context=KriptonBinder.jsonBind();
    try (JacksonWrapperParser wrapper=context.createParser(input)) {
      JsonParser jacksonParser=wrapper.jacksonParser;
      // START_OBJECT
      jacksonParser.nextToken();
      Person result=null;
      if (jacksonParser.currentToken()==JsonToken.START_OBJECT) {
        result=personBindMap.parseOnJackson(jacksonParser);
      }
      return result;
    } catch(Exception e) {
      throw(new KriptonRuntimeException(e.getMessage()));
    }
  }

  /**
   * get instance of shared preferences
   */
  public static synchronized BindSecuritySharedPreferences getInstance() {
    if (instance==null) {
      instance=new BindSecuritySharedPreferences();
    }
    return instance;
  }

  /**
   * editor class for shared preferences
   */
  public class BindEditor extends AbstractEditor {
    private BindEditor() {
    }

    /**
     * modifier for property person
     */
    public BindEditor putPerson(Person value) {
      if (value!=null)  {
        String temp=serializePerson(value);
        editor.putString("person",temp);
      }  else  {
        editor.remove("person");
      }

      return this;
    }
  }
}

Table of Contents

Query definition

Features

Relations

Multithread supports

Modularization

Annotations for data convertion

Annotations for SQLite ORM

Annotations for shared preferences

Clone this wiki locally