Android Live Folder

Posted: February 28, 2012 in Android Posts
Tags: , , , , ,

Live folders have been introduced in Android 1.5 and let you display any source of data on the Home screen without forcing the user to launch an application. A live folder is simply a real-time view of a ContentProvider. As such, a live folder can be used to display all your contacts, your bookmarks, your email, your playlists, an RSS feed, etc. The possibilities are endless! Android 1.5 ships with a few stock live folders to display your contacts. For instance, the screenshot below shows the content of the live folders that displays all my contacts with a phone number:

If a contacts sync happens in the background while I’m browsing this live folder, I will see the change happen in real-time. Live folders are not only useful but it’s also very easy to modify your application to make it provider a live folder. In this article, I will show you how to add a live folder to the Shelves application. You can download its source code and modify it by following my instructions to better understand how live folders work.

To give the user the option to create a new live folder, you first need to create a new activity with an intent filter who action is android.intent.action.CREATE_LIVE_FOLDER. To do so, simply open AndroidManifest.xml and add something similar to this:

<activity
    android:name=".activity.BookShelfLiveFolder"
    android:label="BookShelf">
    <intent-filter>
        <action android:name="android.intent.action.CREATE_LIVE_FOLDER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

The label and icon of this activity are what the user will see on the Home screen when choosing a live folder to create:

Since you just need an intent filter, it is possible, and sometimes advised, to reuse an existing activity. In the case of Shelves, we will create a new activity, org.curiouscreature.android.shelves.activity.BookShelfLiveFolder. The role of this activity is to send an Intent result to Home containing the description of the live folder: its name, icon, display mode and content URI. The content URI is very important as it describes what ContentProvider will be used to populate the live folder. The code of the activity is very simple as you can see here:

public class BookShelfLiveFolder extends Activity {
    public static final Uri CONTENT_URI = Uri.parse("content://shelves/live_folders/books");

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

        final Intent intent = getIntent();
        final String action = intent.getAction();

        if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) {
            setResult(RESULT_OK, createLiveFolder(this, CONTENT_URI,
                    "Books", R.drawable.ic_live_folder));
        } else {
            setResult(RESULT_CANCELED);
        }

        finish();
    }

    private static Intent createLiveFolder(Context context, Uri uri, String name, int icon) {
        final Intent intent = new Intent();

        intent.setData(uri);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON,
                Intent.ShortcutIconResource.fromContext(context, icon));
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);

        return intent;
    }
}

This activity, when invoked with theACTION_CREATE_LIVE_FOLDER intent, returns an intent with a URI, content://shelves/live_folders/books, and three extras to describe the live folder. There are other extras and constants you can use and you should refer to the documentation of android.provider.LiveFolders for more details. When Home receives this intent, a new live folder is created on the user’s desktop, with the name and icon you provided. Then, when the user clicks on the live folder to open it, Home queries the content provider referenced by the provided URI.

Live folders’ content providers must obey specific naming rules. The Cursor returned by the query() method must have at least two columns named LiveFolders._ID and LiveFolders.NAME. The first one is the unique identifier of each item in the live folder and the second one is the name of the item. There are other column names you can use to specify an icon, a description, the intent to associate with the item (fired when the user clicks that item), etc. Again, refer to the documentation of android.provider.LiveFolders for more details.

In our example, all we need to do is modify the existing provider in Shelves called org.curiouscreature.android.shelves.provider.BooksProvider. First, we need to modify the URI_MATCHER to recognize our content://shelves/live_folders/books content URI:

private static final int LIVE_FOLDER_BOOKS = 4;
// ...
URI_MATCHER.addURI(AUTHORITY, "live_folders/books", LIVE_FOLDER_BOOKS);

Then we need to create a new projection map for the cursor. A projection map can be used to “rename” columns. In our case, we will replace BooksStore.Book._ID, BooksStore.Book.TITLE and BooksStore.Book.AUTHORS with LiveFolders._ID, LiveFolders.TITLE and LiveFolders.DESCRIPTION:

private static final HashMap LIVE_FOLDER_PROJECTION_MAP;
static {
    LIVE_FOLDER_PROJECTION_MAP = new HashMap();
    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders._ID, BooksStore.Book._ID +
            " AS " + LiveFolders._ID);
    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders.NAME, BooksStore.Book.TITLE +
            " AS " + LiveFolders.NAME);
    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders.DESCRIPTION, BooksStore.Book.AUTHORS +
            " AS " + LiveFolders.DESCRIPTION);
}

Because we are providing a title and a description for each row, Home will automatically display each item of the live folder with two lines of text. Finally, we implement the query() method by supplying our projection map to the SQL query builder:

public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    switch (URI_MATCHER.match(uri)) {
        // ...
        case LIVE_FOLDER_BOOKS:
            qb.setTables("books");
            qb.setProjectionMap(LIVE_FOLDER_PROJECTION_MAP);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, BooksStore.Book.DEFAULT_SORT_ORDER);
    c.setNotificationUri(getContext().getContentResolver(), uri);

    return c;
}

You can now compile and deploy the application, go to the Home screen and try to add a live folder. I added a books live folder to my Home screen and when I open it, I can see the list of all of my books, with their titles and authors, and all it took was a few lines of code:

The live folders API is extremely simple and relies only on intents and content URI. If you want to see more examples of live folders implementation, you can read the source code of the Contacts application and of the Contacts provider.

You can also download the result of our exercise, the modified version of Shelves with live folders support.

Advertisements
Comments
  1. Barrett Wurdeman says:

    I enjoy your writing style truly loving this internet site. “Nothing is capable of being well set to music that is not nonsense.” by Joseph Addison.

    Like

  2. etupakka says:

    Hi, i believe that i saw you visited my blog so i came to “go back the desire”.I’m trying to to find issues to improve my web site!I suppose its adequate to make use of a few of your ideas!!

    Like

  3. certified nursing assistant exam says:

    Hi my loved one! I wish to say that this post is awesome, nice written and include approximately all significant infos. I’d like to look extra posts like this.

    Like

  4. game presented vizio says:

    Just a smiling visitant here to share the love (:, btw great layout.

    Like

  5. teething says:

    You are my breathing in, I own few blogs and often run out from to post .

    Like

  6. Lavada Schieler says:

    Excellent weblog here! Also your site rather a lot up fast! What host are you using? Can I am getting your associate link on your host? I wish my website loaded up as fast as yours lol.

    Like

  7. film izle says:

    I necessary for this weblog article admin really thanks i’ll glance your following sharings i bookmarked your weblog

    Like

  8. proxy list says:

    In todays news reporting clever journalists work their own slant into a story. Bloggers use it promote their works and a lot of just use it for fun or to stay in touch with friends far away.

    Like

  9. dream builders basketball team says:

    Hey would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a honest price? Cheers, I appreciate it!

    Like

  10. Tory Cool says:

    Hiya, I am really glad I have found this information. Today bloggers publish just about gossips and web and this is really frustrating. A good web site with interesting content, that is what I need. Thank you for keeping this web site, I’ll be visiting it. Do you do newsletters? Can’t find it.

    Like

  11. maryland basketball coach says:

    I would like to thank you for the efforts you’ve put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming also. In fact your creative writing skills has encouraged me to get my own web site now. Really the blogging is spreading its wings fast. Your write up is a good example of it.

    Like

  12. seo made simple says:

    I view something really interesting about your website so I bookmarked .

    Like

  13. music publishing license says:

    I really appreciate this post. I’ve been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thx again! “Every time we remember to say thank you, we experience nothing less than heaven on earth.” by Sarah Ban Breathnach.

    Like

  14. reality porn videos says:

    i bookmarked you in my browser admin thank you so much i will be in search of your next posts

    Like

  15. updates mail says:

    I like what you guys are up too. Such clever work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my web site :). “Royalty has always been an unconscious but all-consuming goal of the European immigrant.” by Vine Deloria, Jr..

    Like

  16. link building tutorial says:

    I think this web site contains some very fantastic info for everyone. “The fewer the words, the better the prayer.” by Martin Luther.

    Like

  17. colleges with nursing programs says:

    Hello there, I discovered your website by means of Google even as searching for a similar topic, your web site came up, it seems great. I’ve bookmarked it in my google bookmarks.

    Like

  18. Poptropica Haunted House Help says:

    You have mentioned very interesting points! ps nice site.

    Like

  19. eliminating credit card bills says:

    Whoah this blog is excellent i love reading your articles. Stay up the good work! You know, many individuals are hunting around for this info, you could help them greatly.

    Like

  20. four micro onde encastrable says:

    Hello my friend! I want to say that this article is awesome, nice written and include approximately all important infos. I would like to peer extra posts like this.

    Like

  21. Della says:

    I really enjoy studying on this internet site, it has got fantastic articles. “The living is a species of the dead and not a very attractive one.” by Friedrich Wilhelm Nietzsche.

    Like

  22. fans for you and me says:

    Awesome Blogpost!

    Like

  23. coach credit card holder says:

    I truly appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thx again!

    Like

  24. i cant get how it is possible to reveal like this amazing posts admin significantly thanks

    Like

  25. Great write-up, I’m normal visitor of one’s website, maintain up the nice operate, and It is going to be a regular visitor for a long time.

    Like

  26. Eva Angelina says:

    Simply a smiling visitant here to share the love (:, btw outstanding style. “Better by far you should forget and smile than that you should remember and be sad.” by Christina Georgina Rossetti.

    Like

  27. Backlinks RSS Submission says:

    But wanna say that this is very useful , Thanks for taking your time to write this.

    Like

  28. copyright and music says:

    Nothing prepared me for the depth and breadth of the knowledge and wisdom contained herein. I humbly request further teachings.

    Like

  29. disque dur externe pas cher says:

    I love the efforts you have put in this, thank you for all the great articles.

    Like

  30. coach credit card holder says:

    What i don’t understood is if truth be told how you are no longer actually a lot more neatly-liked than you might be right now. You are so intelligent. You realize thus considerably in terms of this topic, made me personally imagine it from numerous varied angles. Its like men and women aren’t fascinated unless it’s something to do with Woman gaga! Your individual stuffs great. All the time deal with it up!

    Like

  31. free slots games says:

    I dugg some of you post as I cogitated they were very beneficial extremely helpful

    Like

  32. physician assistant requirements says:

    Great weblog right here! Additionally your web site lots up very fast! What web host are you the usage of? Can I am getting your affiliate hyperlink on your host? I wish my website loaded up as fast as yours lol.

    Like

  33. Terese Gullatte says:

    F*ckinˇ¦ awesome issues here. I am very glad to look your article. Thanks so much and i am looking ahead to contact you. Will you please drop me a e-mail?

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s