Android Data View Adapters Overview

Android APIs provide classes and methods to facilitate displaying data in various forms, such as lists, arrays and custom layouts. The graphic below shows how the various classes and methods interact to produce the desired result.

Some examples of coding and use are:


The data to be displayed can be in such forms as an Array, List, File or SQLite database. If a database is used, a Cursor object is also employed. A simple array of String values might be created and converted to an ArrayList like this:

String[] mStringArray = new String[] { "blue", "green", "yellow",
        "red", "orange", "black", "white", "purple"};
List<String> mList = Arrays.asList(mStringArray);
ArrayList<String> mArrayList = new ArrayList<String>(mList);


Cursor is an interface that provides random read-write access to the result set returned by a database query. Setting up a Cursor for an SQLite database might look like this:

MySQLiteOpenHelper mDatabaseHelper = new MySQLiteOpenHelper(this);
Cursor mCursor = mDatabaseHelper.getDataIntoCursor();
ListView mListView = (ListView) findViewById(;
MyCursorAdapter mCursorAdapter = new MyCursorAdapter(this, mCursor);

class MyCursorAdapter extends CursorAdapter {

    public MyCursorAdapter(Context context, Cursor c) {
        super(context, c);
    // Implement CursorAdapter bindView method.
    public void bindView(View view, Context context, Cursor cursor) {
        String name = cursor.getString(1);
        TextView textView = (TextView) view;
    // Implement CursorAdapter newView method.
    public View newView(Context context, 
                         Cursor cursor, ViewGroup parent) {
        TextView view = new TextView(context);
        return view;
private final class MySQLiteOpenHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "myDatabase";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = 
        "CREATE TABLE IF NOT EXISTS table_name 
        (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("INSERT INTO ddd (name) VALUES ('Name1')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Name2')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Name3')");
    public void onUpgrade(SQLiteDatabase db, 
                          int oldVersion, int newVersion) {
    public Cursor getDataIntoCursor() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;


An Adapter acts as a bridge between an AdapterView and the underlying data for that view. A custom array adapter defined in Java might look like this:

class MyArrayAdapter extends ArrayAdapter<String> {
    HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
    public MyArrayAdapter(Context context, int textViewResourceId,
        List<String> objects) {
      super(context, textViewResourceId, objects);
      for (int i = 0; i < objects.size(); ++i) {
        mHashMap.put(objects.get(i), i);
    public long getItemId(int position) {
      String item = getItem(position);
      return mHashMap.get(item);
    public boolean hasStableIds() {
      return true;

The custom array adapter mArrayAdapter would be instantiated and linked to a ListView mListView with Java code like this:

final ListView mListView = (ListView) findViewById(;
final MyArrayAdapter mArrayAdapter = new MyArrayAdapter(this,
        android.R.layout.simple_list_item_1, mArrayList);


An AdapterView is a view whose children are determined by an Adapter. You might use an AdapterView like this:

private OnItemClickListener mMessageClickedHandler = 
  new OnItemClickListener() {
    public void onItemClick(AdapterView parent, 
                            View v, int position, long id) {
        // Do something in response to the click


View is the basic building block for user interface components. A view occupies a rectangular area on the screen and is responsible for drawing and event handling. A ListView contained in a layout might look like this:

<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:layout_height="wrap_content" >


ViewGroup is a special view that can contain other views called children. A ViewGroup defined in XML might look like this:

<ViewGroup xmlns:android=""
    android:layout_width="fill_parent" >


A layout defines the visual structure for a user interface. A layout might look like this:

<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:layout_height="wrap_content" >


An Activity provides a screen with which users can interact.

public class MyActivity extends Activity {
  protected void onCreate(Bundle savedInstanceState) {
    . . .


A Fragment represents a behavior or a portion of user interface an an Activity. Fragment code might look like this:

public class ArticleFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, 
                             ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, 
                                container, false);

Android App Major Elements

There are many elements that can be included in an Android app. It's helpful to see how these are clustered and interact, as shown in the chart below. Only major elements are shown. The Android Developers Website provides details on the full set of app elements.

The minimum required elements are shown with a red dot. An app with just these elements wouldn't be very useful, but you can see that there are many optional elements that can be added for a variety of functions. 

Intent Messaging

Intents are used to request an action from an app component. Intents are detected and acted upon by Broadcast Receivers.


Activities manage the Displays that app users see. Fragments are modular sections of an Activity that, among other uses, facilitate app adaptation to various screen sizes and dimensions.

User Interface

The User Interface includes a variety of pre-built elements that facilitate constructing screen displays, including: View, Control, Dialog, Notification, Setting, Action Bar, Menu and Toast.


Services perform long-running operations in the background and do not provide a User Interface.

Asynchronous Operations

These elements facilitate asynchronous operations that protect the UI thread from undesirable delays. Loaders make it easy to asynchronously load data in an Activity or Fragment. AsyncTask allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers.

Data, Devices and Sensors

These elements facilitate the access to Data, Devices and Sensors. Connectivity provides access to devices and the Internet.  Content Providers can optionally be used to access databases and internal/external files. Sensors include: GPS, network location, accelerometer, gyroscope and more. 

Reference Elements

These elements are essential for app operation. Libraries provide access to compiled code from Google and other sources. Access to the user Display is built into the operating system. The Manifest include essential information about the app and its elements. Resources include: Layouts, Values and Drawables. Shared Preferences are use to store key-value pairs that act as global variables for the app.

Android Listeners and Toasts

This video, part of my Android Quick Code Access series of posts, explains Android Listeners and Toasts. It's from my course Learning Android App Programming published by InfiniteSkills.

The Java code for the example is below...

import java.util.Random;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ListenerToastMain extends Activity {
    // onCreate method.
	protected void onCreate(Bundle savedInstanceState) {
	    // Initialize display.
           // Declare button variable for Get Answer.
	    Button getAnswer =
	    // Set listener for button.
    // Define OnClickListener for getAnswer button.
    private OnClickListener getAnswerListener = new OnClickListener() {
        public void onClick(View v){
            // Generate answer number.
            Random toastGen = new Random();
            int toastNum = toastGen.nextInt(19);
            // Get answer text.
            CharSequence text = "";
            switch (toastNum) {
                case 1:  text = getString(R.string.answer1);  break;
                case 2:  text = getString(R.string.answer2);  break;
                case 3:  text = getString(R.string.answer3);  break;
                case 4:  text = getString(R.string.answer4);  break;
                case 5:  text = getString(R.string.answer5);  break;
                case 6:  text = getString(R.string.answer6);  break;
                case 7:  text = getString(R.string.answer7);  break;
                case 8:  text = getString(R.string.answer8);  break; 
                case 9:  text = getString(R.string.answer9);  break;
                case 10: text = getString(R.string.answer10); break;
                case 11: text = getString(R.string.answer11); break;
                case 12: text = getString(R.string.answer12); break;
                case 13: text = getString(R.string.answer13); break;
                case 14: text = getString(R.string.answer14); break;
                case 15: text = getString(R.string.answer15); break;
                case 16: text = getString(R.string.answer16); break;
                case 17: text = getString(R.string.answer17); break;
                case 18: text = getString(R.string.answer18); break;
                case 19: text = getString(R.string.answer19); break;
                case 20: text = getString(R.string.answer20); break;       		    
            // Toast answer.
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, text, duration);

Android Broadcast Receiver Concepts and Sample App

This video, part of my Android Quick Code Access series of posts, explains Android Broadcast Receivers.  It's from my course Learning Android App Programming published by InfiniteSkills.

Here's the Java code for the example...

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

// Declare main activity for the application.
public class Main extends Activity {

    // Instantiate BroadcastReceiver.
    private BroadcastReceiver receiver = new BroadcastReceiver(){

        // Define actions to be taken when broadcast is received.
        public void onReceive(Context c, Intent i) {
            // Do the work of the BroadcastReceiver.
            // In this example, a message is toasted to the user.
                           "ACTION_TIME_TICK intent received.", 
    // Initialize the user interface in the onCreate method
    // of the main activity.
    public void onCreate(Bundle savedInstanceState) {  
    // Register the receiver with its filter.
    protected void onResume() {  
        this.registerReceiver(receiver, filter);  
    // Unregister the receiver when the application is paused.
    protected void onPause() {  

P Versus NP Complexity Theory

The P Versus NP issue deals with whether every problem whose solution can be quickly verified by a computer can also be quickly solved by a computer. This is a major unsolved problem in computer science.

In common, practical terms, it deals with how to identify problems that are either extremely difficult or impossible to solve.  In order of difficulty from easy to hard, problems are classified as P, NP, NP-Complete and NP-Hard.

So why do we care? When approaching complex problems, it's useful to have at least some idea of whether the problem is precisely solvable, or if an approximation is the best that can be accomplished. 

Android Release and Device Support Summary

Below is a summary of Android releases and device support.  It shows that by using the  Android Support Libraries you can code your apps to run on a large percentage of Android devices.

For more information on the compatibility Support Libraries see: 

For more information on Device Support see:

Android WebView Combines Native and HTML5 Code

A battle is raging over whether native mobile code apps, such as those for Android and iOS, are a better approach than using HTML5.  Each has its advantages.

There is, though, a way to blend the two in order to take advantages of the benefits each has to offer.  The graphic below shows the anatomy of an app that displays an HTML5 Canvas on an Android screen display.

This app is from the Learning Android App Programming video training course.

The HTML5 Canvas animation displayed is from HTML5 Canvas for Dummies.

You can see the HTML5 Canvas animation by clicking here. To see the JavaScript code that generates the animation, right click on the display page and select View Source Code.

Android Bound Services Using Inter Process Communications

Android Service components can be implemented using a number of mechanisms.  If you want your Service to be able to communicate with other applications running in separate processes, using Inter Process Communications (IPC) is one approach.

The diagram below shows the major classes and methods needed in the binding activity and bound service.  The details of this implementation can be found on the Android Developers Web site here on the Bound Services page

In summary, the major classes involved are:

  • Service - Application component for longer-running operations that do not interface directly with the user.
  • ServiceConnection - Interface for monitoring a service.
  • Messenger - Creates a Messenger pointing to a Handler in one process, and handing that Messenger to another process.
  • Message - Description and arbitrary data object that can be sent to a Handler.
  • IBinder - Interface for a remotable object.
  • Handler - allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Android/PHP/JQuery RESTful JSON MySQL Client-Server Overview

The title of this blog entry is quite a mouthful.  The purpose is to give a broad overview of the moving parts necessary to implement an application with client mobile and desktop devices that interact with a server database to alter and retrieve data.

I won't define all the classes, methods and acronyms on the graphic as they're easy to look up using an Internet search.  There are other choices that can be made for the details of the implementation, but this should provide a starting point for thinking through the necessary elements.

The communication vehicle for client-server interaction is typically the Internet Protocol Suite.


Android Broadcast Receivers

Broadcast Receivers are one of the four basic Android components, along with Activities, Services and Content Providers.  Broadcast Receivers respond to Intents issued by the Android system or Android apps.  It's one way to respond to "things happening" on the user device.

The video below from the training course Learning Android App Programming explains the basics of Broadcast Receivers.

SQL Database Join Operations

It can be challenging to remember the details of all the SQL Join operations.  A convenient way to do this is to use Venn diagrams shown below. For examples of SQL Joins, go here

Commonly used SQL Join operations are:

  • inner join: requires each record in the two joined tables to have matching records.
  • outer join: does not require each record in the two joined tables to have a matching record.

Android Button Listener Code Dissected

Android listeners are the mechanism used to respond to user interaction with a display screen.  Setting up a listener is a very common Android coding task.  Although it can be done with just a few lines of code, it involves a number of elements that must be configured to interact correctly.

The diagram below from the video training course Learning Android App Programming dissects the code to establish a listener for a screen button.

Android Service Methods

Android Services can be configured to run in the same thread as the interface activity or a separate background thread.  The diagram below from the video training course Learning Android App Programming details the methods used to start, stop and send messages to a service.

Android Activity Lifecycle Methods Typical Uses

Understanding the uses of the various Android Activity Lifecycle methods can be a bit tricky.  That is, knowing what do do when.  The chart below shows some typical uses for each of the callback methods.  The chart of from the video training course Learning Android App Programming.

A convenient way to remember the structure of the Activity callback methods is to think of when they're called relative to when the Activity is running:

  • onCreate()   (the only Activity method that must be implemented)
  • onStart()
  • onRestart()
  • onResume()
  • --------------- Activity running
  • onPause()
  • onStop()
  • onDestroy()

Actions taken in the callback methods often relate to the resources they're effecting. Resources that are typically more time consuming to establish, restore or eliminate are dealt with further from when the Activity is running. Conversely, resources that are less time consuming are dealt with closer to when the Activity is running. Here are some examples:

  • --------------- Activity running
  • Variables
  • Preferences
  • Animations
  • Broadcast Receivers
  • Server Connections
  • Databases
  • Background Threads
  • --------------- Activity shut down


Android User Interaction Through Listeners and Toasts

Every Android App interacts with its users.  There are lot's of ways to implement this interaction, but two basic capabilities are listeners and toasts.

Click here to see a video from Learning Android App Programming demonstrating a Listener and Toast to give you a basic understanding of these important and useful techniques.

Android Development Using API Demos

Google provides API Demos apps for various releases of the Android system.  These apps contain hundreds of demos of Android capabilities.  They demonstrate the use of tens of thousands of lines of code and can be a big help to developers as they create their own apps.

However, the API Demos apps are not well documented and it can be difficult to find the code within them for a given function.  In authoring a recently released video tutorial course for Android Developers, I addressed this issue by creating an Excel worksheet that gives developers a tool to better understand the structure of the API Demos and to search the demos based on keywords to find the code they need.

A video explaining the use of API Demos is below...

Describes how to use Android API Demos. From the course Learning Android App Programming published by InfiniteSkills. More information is available at

HTML5 vs. Native App Development

As you're likely aware, there's a big debate going on about whether HTML5 web sites are a better platform for mobile apps than native code development using Android, iOS and Windows.

The main selling point for HTML5 is the write-once-run-anywhere advantage. Web browsers on mobile devices can access web sites from any mobile platform. HTML5 is providing features that allow web page JavaScript code to access phone features like devices sensors and geo positioning. In theory, a well constructed HTML5 web page will look and perform like a mobile device native code app.

However, currently not all device features are available to HTML5 JavaScript code and native code apps have a performance advantage over HTML5 web pages viewed using a browser. Native code apps are presently the dominant choice among developers.

In HTML5's corner, though, the technology is improving and web browsers are ramping up their implementation of HTML5 features. Life would certainly be simpler for mobile developers if they could develop for only one platform, HTML5, instead of multiple native platforms.

Longer term, HTML5 will certainly continue to get better. But so will native platforms. In fact, native platforms may improve more rapidly than HTML5. HTML5 is a global standard developed by the W3C. It takes years of effort to change the standard and have these changes adopted by the various browsers. The individual native platforms (Android, iOS, Windows) can change as quickly as their developers (Google, Apple and Microsoft) want them to. So will HTML5 ever catch up?

Maybe not. Google, Apple and Microsoft have lots of developers and big budgets. They want their products to be competitive ... and that means constant improvements.

So, what's likely to happen? In my opinion, we'll have a blend of the two. In fact, this is taking place today. Native code platforms have Application Programming Interfaces (APIs) that support displaying web pages from within native code apps. Developers can use native code for what it does best and HTML5 web pages for what they do best. The exact mix will shift over time as all the platforms change and improve. 

For developers, this means that separate native code platforms will likely continue to exist. Write-once-run-anywhere will remain an elusive goal probably not realized for a long time, if ever. This doesn't mean that development costs can't be managed or reduced. HTML5 web pages can be developed and used by native code apps where appropriate. Functions specific to those pages can be write-once-run-anywhere. This may not be an optimal solution, but it's the game on the ground.

Smartphone Website with Laptop 2.png