Saturday, December 22, 2012

Android beginner tutorial: Part 28 - Data adapters

Today we'll find out what data adapters are and how to use them.

When developing applications it is often needed to store some sort of data that will be displayed to the user in a ceratin way - a list, a data grid, a drop down menu, etc. The data can be stored in different formats, but to display it in a data widget we need the help of a data adapter.

A data adapter is basically a bridge between data and the widget that displays it. There are multiple adapter classes.

The most simple data adapter class is ArrayAdapter<T>. Before we go further, let's talk a bit about arrays in Android.

Since this used to be an AS3-only tutorial blog, I assume that the readers might not be familiar with all of Java syntax yet. Arrays are declared using this pattern: "Type[] name" or "Type name[]".


String[] names = {"John", "Bob", "Tom"};

This creates an array of string values.

You can achieve the same results using this code too:

String names[] = {"John", "Bob", "Tom"};

Say we have a widget with id "mywidget" in an activity layout that can in some way display data. We can establish a connection between the data and the widget using an ArrayAdapter like this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, names);

The constructor has 3 parameters - reference to the parent Activity, layout to use when instantiating views (there is a number of pre-built layouts to use for that) and the reference to the data holder.

You can also see that I passed <String> next to ArrayAdapter. This is sort of like a parameter - it is used to tell the ArrayAdapter what type of values it is going to have to work with.

This is the basic idea behind data adapters in Android SDK. This will be useful to us in the future tutorials.

Thanks for reading!

No comments:

Post a Comment