- What Is a Widget?
- Widget Hierarchy
- Events and Listeners
- Application Data
- Querying the Display
- Summary
1.4 Application Data
Using application data, you can associate arbitrary named and unnamed data with a widget. In some situations, this can be a useful alternative to subclassing. Given that subclassing at arbitrary places in the Widget hierarchy is strongly discouraged, if you are subclassing in order to add fields to a widget, application data can be used instead.
The setData() method is used to set application data. To allow any object to be associated with a widget, setData() and getData() accept and return objects.
-
setData(Object data) Sets the unnamed application data. The data parameter is associated with the widget and stored in a single unnamed field. This field is for use by the application.
-
getData() Answers the unnamed application data or null if none has been set.
-
setData(String key, Object data) Sets the named application data. The data is stored as a "key/value" pair in the widget. These key/value pairs are for use by the application. The "value" can be any object. If the "key" is null, an IllegalArgumentException ("Argument cannot be null") is thrown.
-
getData(String key) Answers the named application data. The key is used to find the key/value pair. If no such pair exists, null is returned.
The following code fragment associates an unnamed object (the string "Picard") with a widget. The string is then retrieved and the message "Found the captain!" is printed.
widget.setData("Picard"); if ("Picard".equals(widget.getData())) { System.out.println("Found the captain!"); }
The following code fragment associates the key "Android" with the object "Data" and the key "Captain" with the object "Picard". The key "Captain" is used to find the object "Picard", and the message "Found the captain again!" is printed.
widget.setData("Android", "Data"); widget.setData("Captain", "Picard"); if ("Picard".equals(widget.getData("Captain"))) { System.out.println("Found the captain again!"); }
Application data is optimized for space over speed. This means that storing keys and values is memory-efficient, with the result that adding, removing, and retrieving values is somewhat slower. In general, this is a good design trade-off, because most applications tend to store little or no data with their widgets. When data is stored with a widget, it is often a single named or unnamed value. When storing thousands of named values, if you experience performance problems, store a hash table or another data structure as data with the widget and look the values up in the table instead of in the widget.