Permission To Vibrate

Maybe I’m the last one to know this, but I just ran across an interesting little compatibility issue between android 2.2 and 2.3.4. If you want to vibrate the phone on 2.2, no problem, go for it. Run your app on 2.3, BOOM. The app will crash with a java.lang.SecurityException: Requires VIBRATE permission. Yep, on 2.3 you need to explicitly add permission in your manifest.

<uses-permission	android:name="android.permission.VIBRATE"></uses-permission>

Really guys? Couldn’t you log a warning, and then simply NOT VIBRATE the device?

In my case I was just sending a notification and using the default flags, which happens to to include vibrate, if the user has enabled it.

Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_ALL;

By the way, absolutely no mention of this hidden gem in the documentation.

What other breaking changes lie in wait? The adventure continues…..

Posted in Uncategorized | Comments Off

Implementing “Pull To Refresh” in your Android App

From the android-pulltorefresh repo, https://github.com/johannilsson/android-pulltorefresh


“Pull To Refresh” is a UI gesture made popular by the Twitter for Iphone app. It allows a user to refresh a list by pulling down and releasing from the top of the list. IOS developers have had library support for this feature for some time now. Over in Android-land, only the official Twitter app has managed to implement this gesture. Long-promised to be open-sourced, Twitter’s solution is still secret and Android developers have no official means to implement this increasingly demanded feature.

But thanks to Android’s open eco-system, we can build this into our Android app’s using the open-source android-pulltorefresh library developed by Johan Nilson. With thanks to the projects other contributors, his library is capable of producing a UI experience similar to the Twitter app, with support all the way back to 1.5.

The project provides a simple and sufficient example app to demonstrate the library use, but I needed something a bit more robust when I was implementing this in my application. So I thought I’d share my changes here, applying it to example application provided in the project.

Let’s start with a brief explanation of how this works. The android-pulltorefresh library provides a custom ListView that includes a special header. The list is initially displayed with the first item selected. This hides the header from view. The custom ListView responds to touch events so that when you pull down on the list, the header is displayed and handles displaying “pull” and “release” text and animation based on how far you are pulling down. Once its released, the header remains visible with the “loading” message until the view is told the refresh is complete, then it resets the header so its hidden once again.

Getting the basic functionality implemented is straight-forward. First, setup your layout and reference the custom ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <!--
    The PullToRefreshListView replaces a standard ListView widget.
    -->
    <com.markupartist.android.widget.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        />
</LinearLayout>

Now in your ListActivity you need to do 2 things, respond to the refresh request and let the view know when you’re done.
To handle the refresh action the custom view notifies an OnRefreshListener that you can implement to handle your refresh operation.
In the code below you’ll see that it implements the onRefresh method of the listener and wisely executes the refresh on a background thread using an AsyncTask.


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh);

        // Set a listener to be invoked when the list should be refreshed.
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });
        .... <more code>

Once your refresh is complete, notify the view by calling its onRefreshComplete() method. In this example, we call this method on the UI thread once the task is completed.

private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                ;
            }
            return null;
        }

        @Override
        protected void onPostExecute() {
            mListItems.addFirst("Added after refresh...");

            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

            super.onPostExecute();
        }
    }

So that’s basically how the example app from the project is setup. It just initializes a list of Strings and then on every refresh adds a String to the beginning of the list. In a real application we’ll probably need to beef this up a bit.

First let’s take that Task to task and do some real work. In my situation I need to refresh the list by calling an external api and retrieving all the data to be displayed. In this case its actually more efficient just to rebuild the whole list rather than calculating deltas and prepending to the existing list. For this example, assume we have a List as a class-level field managed by a custom ArrayAdapter.
Here’s the first iteration, the list is re-initialized in the task’s onPreExecute() phase, and the work is moved into the doInBackground() method.

private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
		mList = new ArrayList<ListData>();
	}    

        @Override
        protected Void doInBackground(Void... params) {
            JSONArray results = api.getData();
            for (int i=0; i < results.length(); i++) {
                ListData data = parseResult(results[i]);
                mList.add(data);
            }
            return null;
        }

        @Override
        protected void onPostExecute() {
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

            super.onPostExecute();
        }
    }

Seems like that should work ok, but I ran into a problem with this approach. As the user pulls down on the list, the onRefresh() method is called triggering the task, which starts by clearing out the mList array. At the same time, it seems that because of the UI changes, the system appears to be taking some measurements which is causing the getView() method to be called on the adapter that is managing the list. Now because we’ve emptied out the list, the application can exhibit some unpredictable behavior.
Let’s solve this in the next iteration by loading a temporary list in the background, and switching the list once we’re done. We should also consider that its possible we have some error while retrieving the new data, so in that case let’s not refresh the existing list. At least the user will still see their existing data.
Ok, now the GetDataTask looks like this:

private class GetDataTask extends AsyncTask<Void, Void, Void> {

        private List<ListData> localList;

        @Override
        protected void onPreExecute() {
	    localList = new ArrayList<ListData>();
        }    

        @Override
        protected Void doInBackground(Void... params) {

            try{
                JSONArray results = api.getData();
                for (int i=0; i < results.length(); i++) {
                    ListData data = parseResult(results[i]);
                    localList.add(data);
                }
            } catch (Exception ex){
                localList=null;
                Log.e(TAG,"Exception during refresh:",ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute() {

             if(localList != null && !localList.empty()){
                 mList = localList;
                 mListAdapter.notifyDataSetChanged();
             }
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

            super.onPostExecute();
        }
    }

Alright, that’s looking pretty good now. For completeness we really should handle the possibility of the task getting cancelled. This can happen when the user navigates away from the app and the task is killed before its completed. This will cause the onPostExecute() method to not be called and so the onRefreshComplete() method won’t be called. Depending on how the user navigates through the app, they could return to this activity without going through the complete onCreate() lifecycle, and you’ll end up with the screen still showing the “loading” progress message in the header. This is common when using tabs between multiple ListViews.
Also, the documented best practices for implementing an AsyncTask says that in long running background work you should periodically check if the task has been cancelled and try to gracefully quit your work and exit. So let’s get all of that in there.

private class GetDataTask extends AsyncTask<Void, Void, Void> {

        private List<ListData> localList;

        @Override
        protected void onPreExecute() {
	    localList = new ArrayList<ListData>();
        }    

        @Override
        protected Void doInBackground(Void... params) {

            try{
                JSONArray results = api.getData();

                // check if task was cancelled during long api call
                if(isCancelled(){
                  return null;
               }
                for (int i=0; i < results.length(); i++) {
                    ListData data = parseResult(results[i]);
                    localList.add(data);
                }
            } catch (Exception ex){
                localList=null;
                Log.e(TAG,"Exception during refresh:",ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute() {

             if(localList != null && !localList.empty()){
                 mList = localList;
                 mListAdapter.notifyDataSetChanged();
             }
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

            super.onPostExecute();
        }

        @Override
        protected void onCancelled() {
             // reset the UI
             ((PullToRefreshListView) getListView()).onRefreshComplete();
        }
    }

Now that you have a solid refresh implementation you may want to tweak the design of the refresh header. In the sample application they are using the Android “Light” theme. This makes the text black and easy to read. But if you’re using the default “Dark” theme you’ll find the text very hard to see. Here’s a look at the text portion of the refresh header layout, you can see that it references an attribute for the textAppearance style.

        <TextView
            android:id="@+id/pull_to_refresh_text"
            android:text="@string/pull_to_refresh_tap_label"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textStyle="bold"
            android:paddingTop="5dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
        />

Let’s tweak the color of the text to make it readable in our application. To do that, we’ll create a theme that overrides the style used by the textAppearanceMedium attribute. We’ll override this with our own style, which will inherit from the Android TextAppearance.Medium style and override the textColor attribute. Got all that?

First, here’s what Android’s style declaration looks like:

<style name="TextAppearance.Medium">
        <item name="android:textSize">18sp</item>
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">?textColorPrimary</item>
</style>

Now here’s our theme and style declaration:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="android:Theme.NoTitleBar.Fullscreen">
    	<item name="android:textAppearanceMedium">@style/TextAppearance.Medium</item>
    </style>

    <style name="TextAppearance.Medium" parent="android:TextAppearance.Medium">
    	<item name="android:textColor">#FFCDC9C9</item>
    </style>
</resources>

And finally edit the Android Manifest in order to use the new theme:

<application android:name="MyApplication"
                     android:icon="@drawable/icon"
                     android:label="@string/app_name"
                     android:theme="@style/MyCustomTheme">
</application>

And that’s it, everything you you need to implement the pull to refresh gesture, handle the operation and customize the UI.

By the way, the android-pulltorefresh library is made available under the Apache License, V2.0. So you need to maintain any NOTICE files and copyright headers from the source. But you are free to redistribute in derivative works for commercial use.

Posted in Android | Comments Off

LogCat Suddenly Stop Working? Here’s a Solution

This has been stumping me for far too long. I’m in the middle of a heated battle with my latest bug, intel from my logging offensive is starting to roll in, but suddenly LogCat stops producing any further output. A major piece of my artillery is down. Emulator restarts have no effect. Fresh builds, or new deployments appear futile. Usually restarting Eclipse works, but I try to avoid the nuclear option.

But as often happens, one day I had one of those “happy accidents” and just happen to stumble across a solution while working on an unrelated task.  I still don’t know exactly what causes the LogCat to stop working, but it appears that LogCat or maybe Eclipse loses track of what device it was supposed to be tracking.
The solution is simply to remind it.

First, you’ll want to add the Devices view to your current perspective. This will show all devices or AVDs that are currently connected.
Now, anytime that the LogCat stops responding, just select the Device whose output you expect to be shown. Voila, the LogCat window will be populated with all the log statements that have already occurred! So even though it wasn’t being displayed, the logging was still being captured, and will be available to you.  And that’s it, enjoy your logs!

The Android Views Window

The Devices View

Posted in Android | Comments Off

Android: Getting Beyond The Notepad Tutorial

You’ve read the startup docs and completed your first tutorial, and now you’re ready to start creating that killer app that’s been consuming you for all this time. Diligently you start a new Android project in eclipse, open your main Activity and then…

Well what now? It’s not too long before you’re off trying something that wasn’t covered in those Hello World tutorials and suddenly you’re going off-road and can’t find yourself on the map. Soon the trail ends with you spinning your wheels, momentum gone.

While there are many articles out there that promise to “get you started” with Android, its hard to find any that keep you going once you’re on your way. So I thought I’d share some resources that can be used to break through those beginner hurdles or provide a compass when you find yourself in unfamiliar territory.


Diggin The Docs


The Android documentation itself has improved tremendously since I first started working with the 1.0 SDK. You’ll find there’s really a wealth of information once you start doing some digging. Some of these are obvious, but beginners tend to fly right by them, so I’ll just draw your attention to them.


Topics
The Topics area is a nicely curated list of material from the articles, samples and tutorials, grouped by, well, topic.
One of the areas you are likely to first get hung up on is using layouts. Look at the User Interface topic for some good articles, it also usually contains the content from the Layout/Views topic as well.
The New Features topic is always worth checking out, expect new articles a few days to weeks after a new sdk version is released.

Articles
With 30 or so articles, its likely there’s one that touches the area you’re working in. Even if its not exactly what you’re looking for, there’s usually a tip or two that you can pick up and use. The series of Layout Tricks articles and the one on Painless Threading are good reads.

Samples
The sample apps can be used as a starting point for your own app, or just used to study some techniques. Each sdk release brings a few new sample applications that are always worth investigating. Nothing’s been bigger than the new Honeycomb release for tablets, and the Honeycomb Gallery and Renderscript samples give a good look at some of the new features.
But the sample I’ve found to be the most useful is the Api Demos. Its been there since early versions of the sdk, and I still find myself turning to it when I’m first working in a new area. Its a single application that contains many small sample apps, covering virtually all aspects of the basic platform.
When you start the application you’ll see a list of different categories or platform features.

Usually there will be sub categories within each selection and then finally one or more sample apps that demonstrate different aspects of a feature. It’s not always totally intuitive what will be in each category. I’d recommend just flipping though them all to begin with. The Api Demos page in the documentation also is laid out the same as the application, so you can navigate through the docs to also see what’s available. However, I think its better to do it within the application itself, because you will be able to see the samples in action, making it easier to grok what they are trying to demonstrate.

Tutorials
This section is rather sparse, but I’d recommend the Hello Views tutorials. New developers will likely want to focus on the Linear Layout, Relative Layout and List View.

Common Tasks
This section provides quick examples that can be used when first familiarizing yourself with a feature.
It may seem simple, but understanding an Android project’s file structure is always helpful.
The section on Opening a new screen provides some great fundamental knowledge, whereas Referring to localhost demonstrates a very specific task you may require when running an emulator .
I’ve noticed though that old articles are not necessarily kept up to date with changes to the api or best practices, nor are they pruned from the documentation. For example, the section on Threading doesn’t refer to the more recent AsyncTask, which is the preferred method that is explained in the Painless Threading article.
Treat all these resources as a source of knowledge, not necessarily the source of truth.

Android Reference docs (javadocs)

Much closer to the source of truth are the reference docs themselves. I may slip and refer to them as javadocs, because that’s basically what they are. They are generated by the class and method javadoc comments found within the source files. And because the documentation is included in the class itself, there’s a better chance that when the class is changed, the documentation will be updated as well.
It turns out that for many of the important fundamental classes in the sdk, there is some great class level documentation that provides detailed explanations one use of the class.
Along with the AsyncTask I just referred to, a few of exceptional note are the docs on the Activity and View classes.
Activity Life Cycle
Besides just the information on using the specific class, each really becomes a technical article itself. The Activity class doc provides a great primer on the activity life cycle (right), how persistent state is saved, how to start activities, working with permissions, configuration changes and more.

The View class doc describes how common properties are used, how to create a custom view, how views are used in layouts, details on how the system measures and draws views, the basic event handling and threading of views and more.

Beyond the class documentation, some of the package level documentation does better than simply listing the classes and interfaces contained within it. The android.app package documentation provides a brief summary of the important classes as well as links to other sdk documentation where you can find more in-depth information. The new android.renderscript documentation includes a useful overview of this important new Honeycomb feature.

XML AttributesI think one of the bigger challenges is coaxing android into rendering the UI of your app as you’ve designed it. I’m always opening the reference docs to understand the properties available to the layouts and views. Each View or Layout class will include a section that describes the xml properties that are supported and how they are used. Its important to remember that these properties can also be inherited by the parent classes, so make sure to always check what’s available from the super classes.

Tip: Remember to keep in mind the minimum api level you’re targeting. Some properties and methods are not available in older versions. Each release can add many new methods, especially API level 11. Always check the docs!





Android Source
Of course the source of truth is the android source code itself. If you get into creating custom views, adapters or the like, its helpful to see the code of the parent class to understand exactly how to extend its base behavior. Even if you aren’t doing anything that complicated, you’ll probably find yourself at some point running the debugger on your code, tracking down some mysterious issue, and discover the trail runs cold as the debugger steps into the framework classes. It would sure be nice to step into that actual code, where the core of your issue could be revealed.

Turns out it’s not too hard to get the android source exposed in your debugging session thanks to a generous guy who created the Android Sources eclipse plugin for just this use case! Install the plugin by adding the update site into eclipse, and all your projects will automatically have the android source, specific to your targeted api level, available when debugging.

If you’d like a little more direct access to the code, you can browse the repository from the web. However, it’s not as simple as you might think. The Android platform is actually spread across many different repositories, and trying to figure out how to find the class you’re look for can be challenging. Fortunately, 90% of the code you care about is found in the platform/frameworks/base project.

Of course you’ll quickly find that any in-depth investigation of the source using this method is less than ideal. Eventually you’ll just want to have the source locally, maybe even as an eclipse project, so you can easily navigate the code. Roll up your sleeves, this takes a bit of work.

First, know that Android is managed using Git and as said before, is spread across many, many repos. But we only need to get the source from the platform/frameworks/base.git repo. Android provides some instructions on working with source, but that’s geared towards users who are going to be contributing to the platform, and so is more complex than you’ll need.

Explaining how to use Git is beyond this article, but in short, you first clone the remote repo, which creates the complete repository on your local machine. Then you checkout a specific branch from your local repo, corresponding to the api level you are targeting. Now you will have the source code in a local workspace. It’s going to look something like this…

git clone git://android.git.kernel.org/platform/frameworks/base.git android-src
cd android-src
git checkout -b gingerbread remotes/origin/gingerbread

Finally, create a new project in eclipse, choose to base the project on existing source, and point it to your android source directory.


Thinking Outside the Docs


Of course there are plenty of other great resources you can use besides the official Android documentation.

Developer Forums
Since the beginning, Android has used Google Groups as the primary forum for discussions with the developer community. There used to be 2 main groups, android-beginners and android-developers. Today, only the android-developers group is still active, but it’s a great place to ask questions. There are several developers from the core framework team who will occasionally join in the discussions. Of course, many developers have already probably asked a question similar to yours, so first make sure to search the forum and read all similar discussions. I’ve found my questions are usually already answered, or I get enough information to figure it out myself. Plus, you’ll find many of the early posts had much more participation from the framework developers, so you can gain a lot of insight from those older threads.

So what happened to the android-beginners forum? Well, they dropped it in favor of the new default forum of all developers, stackoverflow.com.
So much of the discussion had started moving to Stack Overflow that android finally just formally told everyone to go there with the basic android questions. In order to effectively search the android discussions, use the tag “[android]” in your search. You can view all the latest android discussions at http://stackoverflow.com/questions/tagged/android.

Web Tutorials
The web is full tutorials on various aspects of android, and listing them all here is impossible, so here are a couple that I’ve found helpful.

Java Code Geeks

These guys have put together an impressive 8 part tutorial that builds a full application using the common features many applications will need.

  • Part 1: Main Activity UI
  • Part 2: Using the HTTP API
  • Part 3: Parsing the XML response
  • Part 4: Performing the API request asynchronously from the main activity
  • Part 5: Launching new activities with intents
  • Part 6: Customized list view for data presentation
  • Part 7: Using options menus and customized dialogs for user interaction
  • Part 8: Creating an AppWidget for the home screen

Lars Vogella
Germany’s prolific Eclipse and Java blogger/trainer has put together several good Android tutorials that cover the basics of many features. One thing I really like about his tutorials is that he updates them when new apis are released and also fixes bugs that others point out. And he lists the revision history at the beginning of the article, so you know how current the information is. The tutorial on using the ListView/ListActivity is recommended.

Open Source Apps
Tutorials and samples are great, but nothing beats studying a complete published application. How about one with over a million installs? How about the Foursquare app?

Foursquare AppYep, that’s right, the Foursquare app, foursquared, until a short time ago, was open source. Seems like they took it private in the beginning of the year, but you can still get the code up to that point, and it provides some great examples for UI, notifications, connecting to twitter, working with maps, and, of course, location!

Its hosted on Google Code using Mercurial, which many people aren’t familiar with. If you have used Git (maybe to pull the Android source?), then it’s easy. Simply download and install the Mercurial client to your computer and clone the repo like you would with Git.



hg clone https://foursquared.googlecode.com/hg/ foursquared

This creates a local copy of the repository in the directory foursquared. Then you can create a new Android project in Eclipse based on the /main directory. In order to properly build the code and run it in an emulator, there a few configuration steps required. These have been documented in the README file.


Wordpress AppThe WordPress for Android app is no slouch, with several hundred thousand installs, plus the project is still open and very active. Looking for an example of XML-RPC over SSL? Here you go! This time you’ll need to use Subversion to work with the source.

Aside from the samples in the sdk, Google has also shared some further apps-for-android, containing several 2d gaming apps, use of the accelerometer, a mashup with YouTube, and others.

Looking for more? Doesn’t wikipedia know everything?


Twitter
One of the great things about working with Android is the community around it. People are always the best resource to keep you moving and motivated. And where I go to find this community is Twitter. There’s plenty of Android activity on Twitter, people sharing the latest news, tips, advice and links to great content.
You may want to follow this list of Android developers and enthusiasts that I’m curating. And of course you can also follow me!


This is by no means a comprehensive look at all the Android resources out there – that’s what Google is for! However, I hope it provides a useful guide that can keep you from getting stuck, stay moving, and give you the occasional boost needed to complete that app.

Good Luck!

Posted in Android | 1 Comment

What’s The Opposite Of Prolific?

As a blogger, I’m anything but prolific. The ideas, words and inspiration aren’t the problem. Its the execution, from head to fingers to bytes. I’d say its second only to taxes in the agony department. But here I go, starting another blog. I started my last one many years ago and it was a confusing mix of rants, links and the occasional tech post. I decided I wanted a space that focused on my professional interests, and so here we are, Shared State. If you understand the reference and think, well that’s clever, then you and I are going to get along just fine.

I would love to promise you a consistent flow of new and relevant content, that keeps you coming back week after week. Yeah, I’m not going to do that. I can promise that there will be at least one more post, because, well its almost done. And I have a couple other drafts in the works, so you know, there’s likely to be a few more coming. Someday. And when they do I’ll let you know on Twitter, so don’t kill yourself refreshing this page, ok?

In the business world we call this managing expectations, and now that I’ve got the bar set so low a small child couldn’t limbo under it, I think we can get started.

See you in a bit.

Posted in Uncategorized | Comments Off