Vladimir Vivien's complete blog can be found at: http://vladimirvivien.wordpress.com/
Saturday, November 19, 2011
When creating apps in Android, you have access to numerous data sources. In fact, Android comes with a built-in instance of SQLite, provides access data to local storage, gives direct access to remote resources over HTTP. In additions to these native data providers, you can setup your own application to be a data provider. Since Android does not allow applications to share data directly with one another, you can make your data accessible to (components in your application or) other applications using the ContentAPI. For instance, Android has a phonebook content provider which lets you search, add, modify contacts.
A ContentProvider is a first-class Android component (like Activity, Service, etc). It is registered in the manifest file like any other high-level components. You can read about Android ContentProviders from Android’s website at:
- http://developer.android.com/reference/android/content/ContentProvider.html – API doc
- http://developer.android.com/guide/topics/providers/content-providers.html – Content Provider usage
The intent of this write up is to present a simple approach to create and work with your own ContentProvider. It is not meant to be an introduction to data storage in Android. If you have not used data storage in Android, visit the Android’s developer web site and look for data storage.
ContentProvider Overview
As mentioned above, one of the primary purposes for the use of ContentProvider is data sharing. Since databases and other internal data stores are application-scoped, there’s no way to share information between applications. A content provider lets you expose access to your application’s data in a structured and uniform manner.
ContentProdviders are considered data access objects (a software pattern). Their backing data store can be a database, data from local storage, data from a remote server over HTTP, or a custom data source. For this write up, I will use the SQLite database as the backing datastore for the sample content provider that will be be demonstrated. This will keep things simple since the API for SQLite maps nicely to the method used by the ContentProvider API.
The Example
How to Do It
- Define data model – figure out what will be in stored
- Create a Descriptor class – to help describe the data that you will work with. This is not part of any of the APIs. It is a class that I have used to help with with creation of providers.
- Create a Database Class – the database class is implemented as a
SQLiteOpenHelperintended to help with creation/management of the database instance itself. - Define your ContentProvider – the content provider will use the classes created above to install the database, access, and manipulate the data in it. This is also the class that Activity classes will use to access the data.
Define the Data Model
IDNAMEADDRESSCITYZIP
It’s good practice to define an ID column as an identifier for the data row. The ContentProvider’s URI mechanism uses the ID to refer to saved data entities.
Descriptor Class
- URI Authority – the authority portion of the URI representing this entity. In our example it is “com.favrestaurant.contentprovider”
- URI Matcher – this is an internal registry used to map a URI path (serviced by the ContentProvider) to an integer value.
- Entity Class – an inner static class that represents the entity to be managed by the ContentProvider. In our example, this class is called Restaurant. It exposes meta data such as the entity name, supported URIs, etc.
- Class EntityClass.Cols – the entity class provides an inner class called Cols. As you may have guessed, this class exposes the name of the columns to exposed by the ContentProvider for the entity.
public class ContentDescriptor {
public static final String AUTHORITY = "demo.contentprovider.restaurant";
private static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
public static final UriMatcher URI_MATCHER = buildUriMatcher();
private ContentDescriptor(){};
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = AUTHORITY;
matcher.addURI(authority, Restaurant.PATH, Restaurant.PATH_TOKEN);
matcher.addURI(authority, Restaurant.PATH_FOR_ID, Restaurant.PATH_FOR_ID_TOKEN);
return matcher;
}
public static class Restaurant {
public static final String NAME = "restaurant";
public static final String PATH = "restaurants";
public static final int PATH_TOKEN = 100;
public static final String PATH_FOR_ID = "restaurants/*";
public static final int PATH_FOR_ID_TOKEN = 200;
public static final Uri CONTENT_URI = BASE_URI.buildUpon().appendPath(PATH).build();
public static final String CONTENT_TYPE_DIR = "vnd.android.cursor.dir/vnd.favrestaurant.app";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.favrestaurant.app";
public static class Cols {
public static final String ID = BaseColumns._ID; // convention
public static final String NAME = "restaurant_name";
public static final String ADDRESS = "restaurant_addr";
public static final String CITY = "restaurant_city";
public static final String STATE = "restaurant_state";
public static final String ZIP = "restaurant_zip";
}
}
}
What’s going on…
- The first thing to notice in the code above is the definition of variables
AUTHORITYandBASE_URI. Together these form the URI that identifies the ContentProvider. The URI is used by Android for registering the ContentProvider as part of the application. As you will see later, a ContentResolver class will locate and use the ContentProvider based on the provided URI. - Private method
buildMatcher()creates an instance ofURIMatcherfor the ContentProvider. - Inner class
Restaurantexposes meta data that defines the Restaurant entity managed by the associated ContentProvider. - Furthermore, inner class
Restaurant.Colsdefine meta values for the columns associated with the Restaurant entity.
If none of this makes sense, read on to see how the Descriptor class is used.
The Database Class (SQLiteOpenHelper)
ContentProvider implementation is a database, we will use the SQLLite API here to define the database. The purpose of class RestaurantDatabase is to create, install, and help manage the SQLLite database. The Android’s ContentProvider API (along with the ContentResolver class) uses this class to run DDL scripts to install and update the database. If you implement the onUpgrade() method and change the version of the database, the database will be upgraded automatically next time the code is executed.
The one notable portion of the code below is its use of the ContentDescriptor class (see defined above) to provide meta data the table and fields used in the database.
public class RestaurantDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "fav_restaurnt.db";
private static final int DATABASE_VERSION = 2;
public RestaurantDatabase(Context ctx){
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + ContentDescriptor.Restaurant.NAME+ " ( " +
ContentDescriptor.Restaurant.Cols.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ContentDescriptor.Restaurant.Cols.NAME + " TEXT NOT NULL, " +
ContentDescriptor.Restaurant.Cols.ADDRESS + " TEXT , " +
ContentDescriptor.Restaurant.Cols.CITY + " TEXT, " +
ContentDescriptor.Restaurant.Cols.STATE + " TEXT, " +
ContentDescriptor.Restaurant.Cols.ZIP + " TEXT, " +
"UNIQUE (" +
ContentDescriptor.Restaurant.Cols.ID +
") ON CONFLICT REPLACE)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion < newVersion){
db.execSQL("DROP TABLE IF EXISTS " + ContentDescriptor.Restaurant.NAME);
onCreate(db);
}
}
}
The ContentProvider Class
ContentProvider class with the logic for data access and update. The ContentProvider API exposes several methods for inserting, updating, querying, and deleting data. The example code only implements the insert() and query() methods. Note the usage of the ContentDescriptor to provide naming and configuration meta data for the ContentProvider.
public class RestaurantContentProvider extends ContentProvider {
private RestaurantDatabase restaurantDb;
@Override
public boolean onCreate() {
Context ctx = getContext();
restaurantDb = new RestaurantDatabase(ctx);
return true;
}
@Override
public String getType(Uri uri) {
final int match = ContentDescriptor.URI_MATCHER.match(uri);
switch(match){
case ContentDescriptor.Restaurant.PATH_TOKEN:
return ContentDescriptor.Restaurant.CONTENT_TYPE_DIR;
case ContentDescriptor.Restaurant.PATH_FOR_ID_TOKEN:
return ContentDescriptor.Restaurant.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException ("URI " + uri + " is not supported.");
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = restaurantDb.getWritableDatabase();
int token = ContentDescriptor.URI_MATCHER.match(uri);
switch(token){
case ContentDescriptor.Restaurant.PATH_TOKEN:{
long id = db.insert(ContentDescriptor.Restaurant.NAME, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentDescriptor.Restaurant.CONTENT_URI.buildUpon().appendPath(String.valueOf(id)).build();
}
default: {
throw new UnsupportedOperationException("URI: " + uri + " not supported.");
}
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = restaurantDb.getReadableDatabase();
final int match = ContentDescriptor.URI_MATCHER.match(uri);
switch(match){
// retrieve restaurant list
case ContentDescriptor.Restaurant.PATH_TOKEN:{
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(ContentDescriptor.Restaurant.NAME);
return builder.query(db, null, null, null, null, null, null);
}
default: return null;
}
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
}
What’s going on…
The onCreate()method is called when the provider is instantiated (by theContentResolverclass). It is, in turn, used to bootstrap the database via theRestaurantDatabaseclass (see above) instance db.- The
getType()method uses theContentDescriptor.URI_MATCHER(seeContentDescriptorabove) to lookup the MIME type for a given URI. - All of the data access & update methods (including
query(),insert(),update(), anddelete()) take a URI parameter. The URI provides hints such as the entity (and cardinality) being queried or updated. For instance, in our example, if the URI to passed to the query() method looks likecontent://com.favrestaurant.contentprovider/restaurants/*the method will return all restaurant rows in the database. This is accomplished by using theContentDescriptor.URI_MATCHERto determine how to process the URI.
Using the ContentProvider
Once you have all of your pieces in place, you can access the data exposed by the content provider using the ContentResolver. There are certainly more robust ways to use to access data from a ContentProvier. This write up shows the simplest (non-production ready) way of doing it. You should investigate which way works best for your use (see http://developer.android.com/guide/topics/providers/content-providers.html).
public class FavRestaurantActivity extends Activity {
TextView txtName;
TextView txtAddr;
TextView txtState;
TextView txtCity;
TextView txtZip;
ContentResolver contentResolver;
Cursor cur;
SimpleCursorAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
...
contentResolver = this.getContentResolver();
}
@Override
public void onStop() {
super.onStop();
if(cur != null) cur.close();
}
private void loadContent() {
cur = this.getContentResolver().query(ContentDescriptor.Restaurant.CONTENT_URI, null, null, null, null);
...
}
private void saveContent(){
ContentValues val = new ContentValues();
val.put(ContentDescriptor.Restaurant.Cols.NAME, (this.txtName.getText() != null) ? this.txtName.getText().toString() : null);
val.put(ContentDescriptor.Restaurant.Cols.ADDRESS, (this.txtAddr.getText() != null) ? this.txtAddr.getText().toString() : null);
val.put(ContentDescriptor.Restaurant.Cols.CITY, (this.txtCity.getText() != null) ? this.txtCity.getText().toString() : null);
val.put(ContentDescriptor.Restaurant.Cols.STATE, (this.txtState.getText() != null) ? this.txtState.getText().toString() : null);
val.put(ContentDescriptor.Restaurant.Cols.ZIP, (this.txtZip.getText() != null) ? this.txtZip.getText().toString() : null);
contentResolver.insert(ContentDescriptor.Restaurant.CONTENT_URI, val);
loadContent();
}
}
What is going on…
- First, let me point out that the code used above to access data from the
Activityclass is not optimal for production. You should optimize any io-bound code that has propensity to hang the UI by using an asynchronous task. Nevertheless, the code presented above uses an instance ofContentResolverto access data managed by the backing ContentProvider. TheContentResolveruses the URI value passed in to select the proper ContentProvider registered in the AndroidManifest.xml file (not shown). -
The
saveContent()shows how you can use the Descriptor class to create an instance of ContentValues (from the ContentProvider API) to save data. Each column is mapped to its value using the ContentProvider to provide the column name.
Conclusion
This write up provides a guide for those of you, brave enough, to use the ContentProvider API directly. I have introduced the Descriptor class as a container to register meta data to describe the data element captured by the ContentProvier. The hope is to make using the ContentProvider API more organized and provide some structure when putting your own data access code together.
Friday, October 7, 2011
There is still a great number of Java developers out there who are not doing web apps. They use the JDK’s Java launcher directly to bootstrap their apps using public static void main() (abbreviated thereafter as PSVM). And if you are one of those developers, you understand the implications of having a large classpath. It is not uncommon to see shell command with no less than a dozen jars listed on the classpath.
Of course over the years many options have been provided to help with this issue. One of the most recent is from Java 6 where you can reduce the length of the command to launch your Java application by specifying wildcards values in the classpath as shown below:
$ java -cp path1/*.jar:path2:/*:path3/*.jar package.name.ClassName
This write up proposes an alternative approach where your code loads your application’s classes programatically. This pattern, named Loader/Launcher, separates the loading of your application’s classes from the booting of your application logic. The idea is to provide your own loader class that will load your classpath then delegates further bootstrapping responsibilities to a launcher class. One benefit of this approach is that your command to launch your application can be reduced to something like this (no matter the size of your class dependency graph):
$ java -jar package.name.ClassName
The Loader/Launcher Pattern
The way that the Loader/Launcher pattern works is to de-entangle class-loading concerns from application execution concerns. The loading of classes is handled by a Main class with a PSVM method. The native Java command-line launcher loads the Main class. The execution of the application is delegated to a launcher class that implements the Launcher interface. The Launcher is instantiated and invoked by the Main class.
To implement this pattern, you will need the following high-level components:
- The Launcher interface that will be used as a starting point for your app.
- The Main class where a PSVM method is defined.
- A Launcher implementation to execute the application.
The Launcher Interface
Implementation of this interface is intended to be the starting point of your application’s bootup process. Instead of starting your application directly in the PSVM method, as is done traditionally, you would relocate the logic for your application’s boot up sequence in a class that implements this interface. When the PSVM method is invoked by the native Java launcher, it would delegate the boot sequence of your application to your Launcher instance (see interface below Listing-1).
public interface Launcher {
public int launch(Object ... params);
}
Listing-1
This is a simple interface with a single method, launch(). The method takes an array of objects that can be used to pass in arguments to launcher. The method’s signature makes easy to maintain the semantic of PSVM when using the Launcher.
The Main Class
The Main class is designed to be the starting point for the native Java launcher by exposing a PSVM method. The role of this class, in the Loader/Launcher Pattern, is summed up below:
It creates and loads the application’s classpath. Internally, it instantiates a ClassLoader that is used to load the application’s classpath from a specified location.
Once the classpath is in place, it creates an instance of Launcher, from the classpath, to boot up the application by calling launch().
Listing-2 shows the content of a Main class.
public class Main {
private static String CLASSPATH_DIR = "lib";
private static String LIB_EXT = ".jar";
private static String LAUNCHER_CLASS = "demo.launcher.AppLauncher";
private static ClassLoader cl;
static{
try {
cl = getClassLoaderFromPath(
new File(CLASSPATH_DIR),
Thread.currentThread().getContextClassLoader()
);
Thread.currentThread().setContextClassLoader(cl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Returns a ClassLoader that for the provided path.
private static ClassLoader getClassLoaderFromPath(File path, ClassLoader parent) throws Exception {
// get jar files from jarPath
File[] jarFiles = path.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(Main.LIB_EXT);
}
});
URL[] classpath = new URL[jarFiles.length];
for (int j = 0; j < jarFiles.length; j++) {
classpath[j] = jarFiles[j].toURI().toURL();
}
return new URLClassLoader(classpath, parent);
}
public static void main(String[] args) throws Exception{
Launcher launcher = Launcher.class.cast(
Class.forName(LAUNCHER_CLASS, true, cl).newInstance()
);
launcher.launch(new Object[]{"this string is capitalized"});
}
}
Listing-2
The first thing to notice is the static declarations at the start of the listing. The first three declarations setups the “lib” directory as the location for the classpath, provides “.jar” as the file extension, and specifies demo.launcher.AppLauncher as the name of the Launcher class to load from the classpath. The static code block uses method getClassLoaderFromPath() to initialize a URLClassLoader instance (that points to the lib directory) that will serve as the class loader for the rest of the application.
When the public static void main() method in the Main class is invoked (by the Java launcher), it searches and loads an instance of class demo.launcher.AppLauncher which implements Launcher. Then, the code calls Launcher.launch() to delegate the execution of the rest of the application by passing in a String parameter.
The Launcher Class
The Launcher class is responsible for starting up the application-specific logic. Implementation of the launch() method maintains the same signature as the the PSVM method from the Main class to maintain the familiar semantic. Parameters are passed in as arrays of objects and the method is expected to return an integer. A return value of 0 means everything is OK while anything else means something up to the discretion of the implementor. Listing-3 shows a simple implementation of the Launcher class.
public class AppLauncher implements Launcher {
public int launch(Object ... args) {
String result = org.apache.commons.lang3.text.WordUtils.capitalize((String)args[0]);
System.out.println (result);
return 0;
}
}
Listing-3
How It Works
This implementation uses Apache Commons-Lang to capitalize the value of an argument that was passed in. While this is a simple example, it shows exactly how the pattern would work. When the application is invoked from the command-line using
$ java -jar demo.launcher.Main
The Main class resolves the classpath by loading jars from the jar directory. The classpath directory contains all jars that satisfies the dependency graph of the application. In this example the application depends on the Apache-Commons Lang jar. When Main instantiates its ClassLoader instance, the jar will be added on the classpath and thus be available for use.
An Example
You can download example code that shows how this works from the location below:
An example – https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher
The example comes in three separate projects:
- Launcher-Api – contains the definition of the Launcher interface.
- Launcher-Impl – contains an implementation of the Launcher interface.
- Laucnher-Main – contains the Main class that is used as the starting point of the application.
Conclusion
The Loader/Launcher Pattern is an attempt to decouple two distinct activities that occur when a Java application is started: that of class loading and and application start up. The pattern uses a Main class as the entry point from the Java native launcher and is used to load the application’s classpath from a given location. The act of activating the application is then relegated to a Launcher class. The launcher is responsible for actually starting up the application-specific logic in the code. Some of the benefit of adopting this pattern is, firstly, the tighter control over how classes are loaded. You no longer have to rely on the native Java launcher to resolve your classpath. Another benefit is the separation of concerns for the start up sequence of the app. The pattern provides a location, the Launcher interface, where to define what should happen when the application itself (not loading of classpath) is starting. Hope this was helpful.
Reference
https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher - the example
http://code.google.com/p/clamshell-cli/ - tool that uses this pattern
Wednesday, October 5, 2011
All of us in the tech field (specially those in position to create) have an undeniable responsibility to those who use our creation. Steve showed that our creation can be imaginative, usable, and of quality. He showed us that user experience is also a feature. Usability starts from the moment your users open that box and pull out the shiny new toy and ends with their ability to effectively use your products to be productive, entertained, or enlightened.
The best tribute to Steve is to imitate some of his legacies. So, in your next project, make your creation better. If you are designing an API, add that extra function that makes your developers productive; if you are creating a web site , add that feature that will surprise and make your users smile; if you are creating a new product, plan to make it great, plan to make it usable, plan to make it awesome.
I can only hope that the people at Apple don’t fall prey to the temptation of only pleasing the Street but continue Steve’s long-term strategic vision of bringing quality and imaginative products out to the market. As Apple’s recent history attests to, people will gravitate toward quality and the Street will take notice.
Thank you Steve Jobs
Friday, September 9, 2011
Instead of a pure MVC approach, Android provides a simple Adapter API that lets you bridge views with their underlying data source(s). There are several good examples on the web (search for Android Adapter) on how to use the built-in adapters that come with the android SDK. These links below provide two examples non-trivial examples from the Android documentations that you should check out if this is your first time using adapters:
- http://developer.android.com/resources/tutorials/views/hello-listview.html - shows a simple example on how to use the ArrayAdapter when your data source (as you would guess) is the form of a array (Java type or XML array resource).
- http://developer.android.com/resources/tutorials/views/hello-gridview.html - shows how to create grid view along with an Adapter to provide data for the the view.
Create Your Own Adapters
In non-trivial Android development, chances are you have a complex data graph to maintain states. Rather then trying to fit your data structure to work with the out-of-the-box adapters, it is relatively easy to just create your own. As a measure of practice, you should create a custom Adapter implementation for your views (specially ListView instances). Why? Your own Adapter class will be more flexible and you will add just enough functionality needed and avoid carrying around bloated code.
A Simple Implementation
The following is derived from a simple implementation which prompted this writing. I have a simple class Application which I want to bind to a ListView. Since we are going to use an Adapter we will break down the components as follow: list_layout.xml, item_layout, a data transfer object, and the activity where everything is displayed.
Main Layout – list_layout.xml
This is used for the Activity layout. It contains the ListView instance that will be bound to the adapter.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/my_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false"
android:textFilterEnabled="false"
android:stackFromBottom="false"/>
</LinearLayout>
Row Layout – item_layout.xml
This layout is used by the Adapter instance to generate the view used for each item (row) in the ListView. Use this layout to customize how you want each row in the bounded list view to appear. In this example, we are going to have a simple TextView instance in each row.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12sp">
<TextView android:id="@+id/data_item"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Data Transfer Object
This object is part of the internal object graph that is used to maintain state. It is used by the Adapter as the data source for information bound to the view.
public class MyData{
private String item;
public String getItem(){return name;}
public void setItem(String n){name = n;}
}
The Activity (Abbreviated)
The following shows an abbreviated version of a definition for an Activity class that uses the defined ListView (see above). Although it looks intimidating, this Activity class contains all the basics of a normal Activity class. However, part of the definition an Adapter class used to bind data to the ListView (see class MyListAdapter).
public class MyListActivity extends Activity{
ListView listView;
List<MyData> dataSource;
MyListAdapter adapter;
...
@Override
public void onCreate(Bundle savedInstanceState) {
this.setContentView(R.layout.list_layout);
listView = (ListView) findViewById(R.id.my_list);
dataSource = new ArrayList<MyData>();
adapter = new MyListAdapter(this, R.layout.item_layout, dataSource);
listView.setAdapter(adapter);
...
}
// private Adapter for my list
private static class MyListAdapter extends BaseAdapter {
private Activity parentActivity;
private int itemLayoutId;
private List<MyData> dataSource;
private LayoutInflater inflater;
// constructor for adapter
public MyListAdapter(Activity activity, int layoutId, List<MyData> ds){
parentActivity = activity;
itemLayoutId = layout;
dataSource = ds;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int pos, View convertView, ViewGroup parentView){
View view = null;
if(convertView == null){
view = inflater.inflate(itemLayoutId, parentView, false);
TextView textView = (TextView)view.findViewById(R.id.data_item);
String data = dataSource.get(pos).getItem();
textView.setText(data);
}else{
view = convertView;
}
return view;
}
}
}
If you have implemented an Activity before, the beginning should look familiar. In the onCreate() method, we bind the Activity to the main layout my_list. Next we pull out the ListView instance from that layout and set its adapter to an instance of the custom adapter class defined by MyListAdapter.
The class MyListAdapter is simple. It extends the BaseAdapter which is provided by the SDK as a starting point for custom adapters. You must override public method getView() as shown above. This method will be called by the View instance, bound to this adapter, to draw the portion of the View that displays the data at the specified position in the data set. In the snippet, we use and Inflater to reconstruct the View represented by R.layout.item_layout. Then bind the data to a TextView instance contained in the layout. The entire inflated View instance is returned by getView() to be used by the parent view.
Beware!
While getView() provides the core logic for your adapter to expose your custom data. I found that it’s also important to override the following methods shown below. If not you will spend hours trying to figure out why your list is not displaying properly.
private static class MyListAdapter extends BaseAdapter{
...
@Override
public int getCount() {
return (dataSource != null) ? dataSource.size() : 0;
}
@Override
public Object getItem(int idx) {
return (dataSource != null) ? dataSource.get(idx) : null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds(){
return true;
}
@Override
public int getItemViewType(int pos){
return IGNORE_ITEM_VIEW_TYPE;
}
@Override
public int getViewTypeCount(){
return 1;
}
}
While these methods look simple, they are used by the Adapter API to figure out how render the bounded views. You can find more information about them from the SDK Android doc page for Adapter.
I hope this was helpful to your Android development efforts! I have written enough. Until next time!
Saturday, June 18, 2011
I haven’t written down my thoughts in so long using blog that I forgot I had a blogging website. Last couple of years have been moving fast so I adopted a medium that moves just fast, Twitter. However, Twitter can be noisy. While Twitter is a good source for info junky like myself, the stream of text that it provides tend to drown quickly good ideas and posts as they are swept away with every refresh. So, to provide a more permanent place to my rant, ideas, and thoughts, I have decided to return back to blogging.


