Sunday, February 5, 2012

Building an line-of-business Android app - Part 1

How to write a simple application that shows a list from a content provider with SQLite as backend.
I will assume you have configured the SDK and that you know Java.

Grab the project's code here: http://ge.tt/9Qt6sDD


Creating a new project


First, create a new project in Eclipse, I'll call it yourapp-android, and I'll use the package name com.you.yourapp, using the Android 4.0 SDK but I'll target 2.2 devices.



















Now we'll create a class to helps us to setup a database for our content provider. We'll call this class com.you.yourapp.YourAppDatabase:


package com.you.yourapp.providers;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class YourAppDatabase extends SQLiteOpenHelper {


private static final int VERSION = 1;
private static final String NAME = "yourapp.db";
private Context context;


public YourAppDatabase(Context context) {
super(context, NAME, null, VERSION);
this.context = context;
}


@Override
public void onCreate(SQLiteDatabase db) {
try {
runScript(db, "create_db.sql");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}


private void runScript(SQLiteDatabase db, String scriptName)
throws SQLException, IOException {
InputStream inputStream = context.getAssets().open(scriptName);
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);


String line = null;
while ((line = bufferedReader.readLine()) != null
&& line.trim().length() > 0) {
db.execSQL(line);
}
try {
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
}

I highlighted that I'll use a file called create_db.sql. This file will be placed under the assets folder and you can put this inside it:

CREATE TABLE "customers" ("_id" INTEGER PRIMARY KEY, "name" TEXT, "balance" REAL);
INSERT INTO "customers" VALUES (1, "Customer 1", 400);
INSERT INTO "customers" VALUES (2, "Customer 2", 0);

This is standard SQLite syntax. Please note that I'm using _id. This is because this column name is used by list view controls to get the item id.

Now, I will create a content provider. Android uses content URIs to identify data within your app. I will use one simple URI to point to my customers' table: content://com.you.yourapp/customers.

You might want to add more tables later, so I'll show you how I structure my code to handle one table under a single content provider, but you can add a second table if you want.

This will be the com.you.yourapp.providers.YourAppContentProvider class:

package com.you.yourapp.providers;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

public class YourAppContentProvider extends ContentProvider {
private static UriMatcher matcher;
private static final int CUSTOMERS = 1;
private YourAppDatabase databaseHelper;

static {
matcher = new UriMatcher(UriMatcher.NO_MATCH);

matcher.addURI(Customers.CONTENT_URI.getAuthority(),
"customers", CUSTOMERS);
};

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
switch (matcher.match(uri)) {
case CUSTOMERS:
return Customers.delete(databaseHelper.getWritableDatabase(), uri,
selection, selectionArgs);
}

return 0;
}

@Override
public String getType(Uri uri) {
int code = matcher.match(uri);

switch (code) {
case CUSTOMERS:
return Customers.TYPE;
}

return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
switch (matcher.match(uri)) {
case CUSTOMERS:
return Customers.insert(databaseHelper.getWritableDatabase(), uri,
values);
}

return null;
}

@Override
public boolean onCreate() {
databaseHelper = new YourAppDatabase(getContext());

return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int code = matcher.match(uri);

switch (code) {
case CUSTOMERS:
return Customers.query(databaseHelper.getReadableDatabase(), uri,
projection, selection, selectionArgs, sortOrder);
}

return null;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int code = matcher.match(uri);

switch (code) {
case CUSTOMERS:
return Customers.update(databaseHelper.getReadableDatabase(), uri,
values, selection, selectionArgs);
}

return 0;
}
}

This class ends up invoking methods in the Customers class, use this code for that one:

package com.you.yourapp.providers;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class Customers {
public static final String TABLE_NAME = "customers";
public static final String[] COLUMNS = new String[] { "_id", "name", "balance" };
public static final int ID = 0;
public static final int NAME = 1;
public static final int BALANCE = 2;
public static final Uri CONTENT_URI = Uri.parse("content://com.you.yourapp/customers");
public static final String TYPE = "vnd.android.cursor.dir/vnd.com.you.yourapp.customers";

public static int delete(SQLiteDatabase db, Uri uri, String selection, String[] selectionArgs) {
return db.delete(TABLE_NAME, selection, selectionArgs);
}

public static Uri insert(SQLiteDatabase db, Uri uri, ContentValues values) {
db.insert(TABLE_NAME, "", values);

return CONTENT_URI;
}

public static Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return db.query(TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
}

public static int update(SQLiteDatabase db, Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return db.update(TABLE_NAME, values, selection, selectionArgs);
}
}

Now we must expose this content provider in our AndroidManifest.xml file, add the following fragment to it:

 <provider
     android:name=".providers.YourAppContentProvider"
     android:authorities="com.you.yourapp"
     android:label="@string/yourapp_provider_label" >
</provider>

It is referencing a string which we didn't add yet, so you'll open your res/values/strings.xml file and add the following element:

<string name="yourapp_provider_label">YourApp</string>






This string is user visible and describes the content provider data.


Displaying our content providers data

Now, we'll add an activity to show this data we have. Create a class named com.you.yourapp.CustomersListActivity:

package com.you.yourapp;

import com.you.yourapp.providers.Customers;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;

public class CustomersListActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Cursor cursor = getContentResolver().query(Customers.CONTENT_URI,
Customers.COLUMNS, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.two_line_list_item, cursor, new String[] {
Customers.COLUMNS[Customers.NAME],
Customers.COLUMNS[Customers.BALANCE] }, new int[] {
android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
}
}

And we will declare it in our AndroidManifest.xml file:

<activity
    android:name=".CustomersListActivity"
    android:label="@string/customers_list" >
</activity>

And also, set up the customers_list string we've just referenced (this again, in res/values/strings.xml):

<string name="customers_list">Customers</string>

Now, we'll modify our HomeActivity class to display a list of activities that we can do in our app, in this case, only invoking the CustomersListActivity:

package com.you.yourapp;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HomeActivity extends ListActivity {
public class HomeActivityItem {
public Intent intent;
public String title;

@Override
public String toString() {
return title;
}
}

private HomeActivityItem[] items;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

ArrayAdapter<HomeActivityItem> adapter = new ArrayAdapter<HomeActivityItem>(
this, android.R.layout.simple_list_item_1, android.R.id.text1);
setListAdapter(adapter);

items = getActivityItems();

for (HomeActivityItem item : items) {
adapter.add(item);
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
startActivity(items[position].intent);
}

private HomeActivityItem[] getActivityItems() {
HomeActivityItem[] array = new HomeActivityItem[1];

array[0] = new HomeActivityItem();
array[0].title = getString(R.string.customers_list);
array[0].intent = new Intent(getApplicationContext(),
CustomersListActivity.class);

return array;
}
}

And that's it for now, next time, this series of post will have more fun, as we'll add account management and synchronization =)

Thank you for reading!

No comments:

Post a Comment