I think, therefore I blog

Simple Android File Chooser

By , 3 June 2015

Simple Android File Chooser

Surprisingly, the Android API doesn't include a file chooser. I'm not sure why that is, I guess the developers don't want to make the assumption that the device has a user filesystem available. Anyway, it's not my job to speculate on what the Android developers talk about over lunch. I just need a file chooser.

It seems like there are a few options out there but I wanted something uber simple and ultra light. It's just for users to select an import file.

My solution is a single Java class utilising regular android Dialog and ListViews. It just wires up the event handlers to read from the disk and refresh the list. You provide a FileSelectedListener implementation to handle the file selection event. Menial stuff that you don't want to bother implementing yourself. It can be used like this:

new FileChooser(activity).setFileListener(new FileSelectedListener() {
    @Override public void fileSelected(final File file) {
        // do something with the file

Here is the FileChooser class which you can cut and paste into your project. Public domain code so do what you want with it.



13 comments, post a comment!

OrmLite DAO Factories And Connections Made Easy

By , 7 June 2014

OrmLite DAO Factories And Connections Made Easy

OrmLite comes with some classes to help manage connections, but unfortunately they are poorly named and just plain confusing. For example, OpenHelperManager manages connections - and see if you can guess how that relates to OrmLiteSqliteOpenHelper or the DaoManager. This short blog gives you some simple code to make your API more intuitive and readable.

Connection management and singleton objects are never a simple combination. That's why we do things like abstraction and encapsulation. What I set out to do was have an API that looked like this:

    CategoryDAO dao = CategoryDAO.connect(context);
    List categories = dao.getCategories();

To get there it helps to know what is going on under the hood. So let's reverse engineer some of those oddly named OrmLite classes:

  • OrmLiteSqliteOpenHelper (Database Definition). Defines how to connect to the database and create and update the tables. This is where the real connection object lives. 
  • OpenHelperManager (Connection Management). Keeps count of the number of times the database (connection) has been requested and released. When the count goes to zero it releases the database resources and when it goes back up it recreates them.
  • DaoManager (Singleton Management). Ensures that only one instance of a DAO is created for a given connection. Most apps will only connect to one database, so this effectively implements a singleton pattern. It is necessary because creating DAOs is expensive in Android due to the reflection involved.

Now, we can tie these objects together to implement the API we'd like. Here's an example:

public class CategoryDAO extends BaseDaoImpl<Category, Integer> {
    public CategoryDAO(ConnectionSource source) throws SQLException {
        super(source, Category.class);
     * Static instantiation methods. The database connection is accessed via
     * the OpenHelperManager which keeps a count of the number of objects
     * using the connection. Thus every call to connect() must be matched by
     * a call to release() once the session is done. 
    public static CategoryDAO connect(Context context) {
        return with(OpenHelperManager.getHelper(context, Database.class)
    public static CategoryDAO with(ConnectionSource connection) {
        try {
            return (CategoryDAO) DaoManager.createDao(connection, Category.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);

     * Releasing the DAO flags the connection manager that the DAO is no
     * longer using the connection. When the connection count is zero, the
     * connection manager will close the database.
    public void release() {

Now our target code above will run, OrmLite will manage the singletons and the OpenHelperThingy will reuse connections across the DAOs.  The alternative factory method CategoryDAO.with(connection) is useful for unit tests, or for using one DAO inside another like this:

    public void update(Category category) {

Here, we just reuse the same connection as the host DAO. For a unit test, you can set up the connection to the test database manually (or use Robolectric to mock the Android context).

Let me know if you think there is anything wrong with this pattern in the comments below. In my experience readable code goes a long way.

No comments yet, be the first to comment!

How To Make Android Spinner Options Popup in a Dialog

By , 28 May 2014

The earlier versions of Android always showed spinner options in a dialog. Then I think devices got bigger and the powers that be decided to use a dropdown list for spinner options instead of a dialog. It's a sensible choice because the dropdowns look and operate better than the dialog - sometimes.

It's the sometimes that is the problem. For lists with a lot of data it makes better sense to use a full screen dialog than a small dropdown. The screenshots below show how much better the usability of a dialog selection is for our app, The Game Of Your Life.


2 comments, post a comment!

How To Remove The Facebook Android Sharing Intent

By , 2 May 2014

How To Remove The Facebook Android Sharing Intent

I don't really care why Facebook made a mess of their Android sharing intent. Other developers have already pointed out that their iOS sharing works fine, but their Android product only allows you to share URLs and not text. My guess is they are trying to force developers onto their API because, you know, force makes people so much more motivated and creative and all that.


The real problem is that it makes your app look broken, and fortunately there is a simple solution:

Dump Facebook.

Just cut and paste the code below to launch your share intents and Facebook will not be listed as an option. That way you won't look bad when their share page comes up blank.


3 comments, post a comment!

How To Check If The Software Keyboard Is Shown In Android

By , 21 February 2012

How To Check If The Software Keyboard Is Shown In Android

Here is a method to detect if the soft keyboard is visible on the screen in Android. All the other methods I have seen test the height of screen elements to guess whether it is displayed. This doesn't work for keyboards like WifiKeyboard which is an invisible keyboard.

This method uses the callback result of InputMethodManager.showSoftInput() to determine if the keyboard status changed. This is suitable for me because I need to call showSoftInput() anyway if the keyboard is not shown. The result from the operation needs to be polled because it is asynchronous. This example only polls 500 milliseconds and assumes that anything longer than that is caused by the keyboard being loaded and rendered.

Here is how the code is used:

// try to show the keyboard and capture the result
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
IMMResult result = new IMMResult();
imm.showSoftInput(editText, 0, result);

// if keyboard doesn't change, handle the keypress
int res = result.getResult();
if (res == InputMethodManager.RESULT_UNCHANGED_SHOWN ||
        res == InputMethodManager.RESULT_UNCHANGED_HIDDEN) {


9 comments, post a comment!

Fast Notes, The Fastest Note Taking Application For Android

By , 21 January 2012

Fast Notes, The Fastest Note Taking Application For Android

Some time ago I wrote a little review of several of the most popular Android note-taking apps. I ended up have three different apps installed because I couldn't find one that did just what I wanted.

So I wrote Fast Notes.

Fast Notes lets you take notes with just a single button press.

Lauch Fast Notes by long-pressing the search button or by pressing the icon in your launcher. Enter your note and long-press on a tag to save and exit. Voila, finito. Have you ever taken notes so quickly? You can also use the back button to save and exit.

Long press the search button to launch. Long press a tag or press back to save and exit.

I use Fast Notes to keep my todo lists, jot down ideas, collect phone numbers, organise my projects, record my expenses, make checklists, keep a diary, help remember people's names, learn new words, share tweets, write blogs, collect quotes and even to work on my book whenever I have a few spare moments.



No comments yet, be the first to comment!

Android ORM / JPA

By , 19 December 2011

Android ORM / JPA

Coming from the server-side, I find it hard to live without ORM (Object-Relational Mapping) such as JPA. Now that I've started writing Android Apps, I set about finding a JPA ORM tool for Android.

Here is a comparison of the tools I found that do ORM and are lightweight enough for use with Android.

  Annotations DB Ops Size License Docs Age
OrmLite JPA or custom DAO or Entity 200kb Open docs 1yr
ORMAN JPA-like Entity 170kb Apache2 wiki 2yrs
greenDAO N/A Codegen DAO or Entity <100kb Apache2 docs  
ActiveAndroid JPA-like Entity   $20 wiki  
AndrORM None       docs 1yr

"DB Ops" refers to how database operations such as persist() and update() are handled. Normally either by a DAO (data access object) or by the entity themselves.

Handling Large Data Sets

Performance counts - especially since I need to handle large data sets. I don't want to load 3000 records into memory at once when the device only has room to display 10 at a time. Native Android supplies a Cursor to interate large data sets, and some ORM tools provide their own method too.

greenDAO has Query.lazyList() and OrmLite has DAO.iterator(Query) to do this, however Android adapters do not bind to an iterator so a custom adapter would need to be written in any case. There is a thread online that discusses this, however I think I can rig up a something similar to my LazyList for JPA to make this happen.


I've started my project with OrmLite because it is the most mature. Lazy loading query results will need some custom code, but in the long run I think it will be better than polluting my code with column names and SQL hacks.

greenDAO was a good candidate from the performance perspective, but really I want to write my Entities myself so I can add the methods that I need.

Android Note Taking Apps Review

By , 18 September 2011

I think a lot. Probably too much. I also like writing and have discovered that my phone is actually my preferred medium for writing. It's portable and you can edit and organise content in a way that you can't with paper notepads.

Update: Since writing this article I have developed my own note taking application called "Fast Notes" which is better than all these note taking apps. Read more...

A good keyboard like Slide IT lets you write at an acceptable speed, but I had a hard time finding a notepad app that I really liked. Here is what is was looking for:

  • Quick add button. Essential. I only want to have to click once to get my ideas down. Any more than that and I've already lost patience or lost my train of thought.
  • Tags. ideas, contacts, articles, stories, poetry, memories etc etc. I want to be able to find old notes, view them coherently and see which ones need attention.
  • Share. A lot of the stuff I write on my phone ends up on the web or in something bigger I am working on. I need a way to get individual notes off my phone.
  • Export or Backup. I backup important stuff from phone to my laptop regularly and my notes are important.
  • View Note Widget. For frequently used or modified notes, such as my todo list, collection of new words, or my contact details for my new friends to copy.
  • Notes Without Subjects. Adding a subject is an extra click and in that time I'm prone to forgetting what I was thinking about. Also, if I do want a subject for a note, I won't normally know what it is until AFTER I have written it.

Here is my short list of good note taking apps, and their features.


No comments yet, be the first to comment!


Join Over 1000 Subscribers

I write every Sunday about travel, psychology, and technology. Thousands of people just like you have already subscribed—and for good reason. It'll change your life. And it's free :)

Read a Good Book

“A spellbinding true story of love, passion and adventure. One can’t help but be swept away by 100% Love Guaranteed.” —Dr Tammie Matson, author of Elephant Dance.

Chat For A While

Your Vote Matters

Which animal will take over when humans go extinct?