library / org.akop.kotx.tools / Bundler

Bundler

object Bundler

Puts/gets annotated fields of an object to/from a Bundle (types must be compatible/supported).

For instance, for an activity with the following fields:

@Bundler.Storable
private val items = ArrayList<String>()
@Bundler.Storable
@Bundler.Default(int = 5)
private var count: Int = 0

to read the values:

savedInstanceState?.getFields(this)

to write the values:

outState.putFields(this)

Bundler takes care of writing both 'items' and 'count' to 'outState' and reading values from 'savedInstanceState', including setting 'count' to 5 if the value is missing.

Note that while 'items' is a final variable, Bundler will still restore the contents of the list. This allows you to avoid making collection fields non-final, or resorting to tricks such as the following:

items += state?.getStringArrayList("options") ?: emptyList()

getFields can also be called on a null receiver, in which case it will set 'count' to the default value of 5 if 'savedInstanceState' is null:

savedInstanceState.getFields(this) // note: no '?' after savedInstanceState

Annotations

Default

annotation class Default

Annotation specifying the default value for primitive types. Must be specified in conjuction with Storable, otherwise it has no effect.

Storable

annotation class Storable

This annotation enables get/put operations for the field. Key when writing to Bundle is the name of the field itself, unless name is set to something other than empty string.

Functions

getFields

fun getFields(inState: Bundle?, obj: Any, keyPrefix: String? = null): Unit

For each field tagged with Storable, attempts to read the value from inState. Expected key is the name of the field, (unless overridden by Storable.name), optionally prefixed with keyPrefix.

putFields

fun putFields(outState: Bundle, obj: Any, keyPrefix: String? = null): Unit

For each field tagged with Storable, writes the value of the field to outState. The key used will be the name of the field (unless overridden by Storable.name), optionally prefixed with keyPrefix.