Parse CSV files easily with JavaCSV

Though it is much more likely you’ll get your data via a json / xml feed, sometimes it becomes necessary in the course of development events to parse a CSV file.  If you find yourself in this situation, here’s a nice library that will make the process as painless as can be.

JavaCSV is a library born out of the .Net DataStreams framework.  It promises good performance, low resource usage, and near unparalleled scalability (I have yet to test them out on the last claim, but so far I’ve gotten good mileage from the library).  Usage is quite simple:  just grab the .jar from SourceForge, import it into your project as described in Adding an External .jar to your Project, and read your file via the CsvReader class.  Here’s a snippet where I’m reading a file from the /assets folder within an AsyncTask:

protected Integer doInBackground(Void...voids){
// load the .csv file from assets
try {

CsvReader fileReader = new CsvReader(getAssets().open("file.csv"), Charset.defaultCharset());
fileReader.readHeaders();
while(
fileReader.readRecord()){
String unitName = units.get("")

}
} catch (IOException e) {
// TODO Handle Failure to get file
}
return numUnits;
}

Got any libraries you’ve found really useful in your Android development?  Let us know in the comments or over at twitter @droidweb!

Android Snippet: Adding an External .jar to your Project

Android snippets are a new section of Droidweb which detail a simple process in Android Development. However, in spite of their size, don’t dismiss these mini-tutorials! The methods they describe are pretty handy for any serious Android developer. Got an Android tip / trick you’d like to see here? Leave us note in the comments below or tweet @droidweb!

Occasionally you’re going to need to reference other people’s code (OPC) in your Android projects.  Usually this is done in one of two methods: either you import the other project as a library project (if you’ve ever used ActionBarSherlock, you’ve done this), or you include the project as a .jar file.  In today’s Android snippet we’re going to focus on the later.  The process is really simple (a drag n’ drop and a right click is all you need to do), but not doing this properly can lead to headaches at run time.

Things you’ll need:

  • .jar file of the library you intend to import.  Usually this is a downloadable from the site of whatever project you’re making use of

Steps

  1. Copy the jar to your Android project’s /libs folder
  2. Right click the jar and choose “Build Path > Add to Build Path’”
  3. You’re done.  Happy Coding!

Thanks to Vinayak.B over at stackoverflow for this quick tip.  See original post.

Fix @Override Errors in your Eclipse Console

Often when importing Android code into my Eclipse workspace, I find that there are a lot of new ‘errors’ introduced to the code.  These errors were closely linked to my overriden classes (something you’ll find quite often in android code) and read “The method X must override a superclass method” .  For the longest time I’ve wondered how to reliably fix those bugs (until now I had been removing and re-adding the @Override keyword as appropriate to make the compiler shut up).  This morning I stumbled across a Stack Overflow thread that finally solves this problem.

You see, the problem is related to which version of Java the code is checked for compatibility errors against.  Eclipse defaults to using Java 1.5, which only allows the use of interface methods if super() is called.  Java 1.6 allowed the use of the @Override keyword to designation the interface implementation which is current standard way of overriding interface classes in Android coding.

To fix your problem you just need to do a bit of tinkering in the project settings in Eclipse.  Go to your project preferences and under Java > Compiler set the java compiler to 1.6.  While this might fix the error, it is more likely that you’re going to have to change the project specific value for compiler level as well.  Select ”Configure project specific settings” and change the java compiler value there to 1.6 as well.  After an automatic rebuild of your project, you should see all of those pesky error messages disappear!

ActionBarSherlock Compatibility Library upgraded to v. 3.5.0

Developers rejoice! One of my favorite Android libraries to date has recently been upgraded to becoming evenmore awesome than before. Jake Wharton’s ActionBarSherlock library has been updated!

ActionBarSherlock is an extension of the compatibility library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API.  It allows the easy addition of the action bar Android UI paradigm to applications without having to worry about compatibility with older versions of Android.  I am a strong supporter of this paradigm and try to use it whenever possible!

 

From his Google Plus:

Major updates in this version:

  • Completely redone menu and action item support. This has been backported from the progress made on ABS 4.0 and provides a much more stable and logical layout of action items and management of the menu.
  • The compatibility library base has been updated to r6. I have also re-added the *Compat classes that were duplicated by this library and marked them as deprecated.

Download the new version from http://abs.io/. The samples on GitHub and the Android Market will be rolling out this evening as well.

Updating your projects making use of the old library is ridiculously easy.  Just download the new library and any desired .jar files, add the library as a project to your eclipse setup, and replace the references in your project to the old libraries with references to the new libraries.

Do you have any experiences using the ActionBarSherlock Library?  Would you like to see a guide for how to get up and running on ActionBarSherlock?  Drop us a comment below or tweet us @droidweb!

Powerpoint: Android UI Design Tips

Here’s a presentation I found floating through my twitter stream recently. As a developer, it has some useful information you should think about before designing your next application.

Have any design tips? Design questions? We’d love to hear them; just fire us a comment below, or drop us a message via twitter @droidweb

Dealing with JSON in Android

Much like their web-based kin, mobile applications rely on data to make them work. Most applications require calls to an api or other data source, to make themselves useful. Whether it be a call to an RSS feed in your favorite news application, a call to a private API to make your favorite online service app work, or just a database connection to run your favorite MMO game, data is crucial to the mobile application.

When you deal with data pulled from an online source, it usually comes in one of two formats, either XML or JSON. Today we’re going to look at how to deal with JSON, and I’m going to introduce you to some tools I use to make the process as painless as possible.

Firstly, what is JSON? JSON stands for JavaScript Object Notation. It is a “lightweight data-interchange format” used transfer data between servers and client applications. JSON is touted as being XML’s low-fat brother, as it doesn’t use the sometimes bloated tag structure that XML does. Instead, data is organized into objects and arrays. Objects may contain arrays and vice-versa. Quite simply put, objects are unordered name: value pairs where the name and value are separated by a colon and the pair is separated by a comma. Arrays are denoted by brackets “[]“. For a complete explanation of JSON, including examples, check out either the wikipedia entry or the JSON.org website

Now that we know what JSON is, how do we use it? There are many ways to process JSON, including via third party libraries. However I prefer to keep things simple and handle the data using the built in java library code. Generally I make a call to a URL which returns the JSON string via an ASYNCTask (gotta keep that URL processing out of the main UI thread). I then create a JSONObject from that string and parse on the fly using a combination of .getJSONArray(), .getJSONObject(); and custom getObject() methods available through the default org.JSON.* libraries.

While writing the code for processing JSON on the fly, I find a few tools out there helpful:

JSON Lint (http://www.jsonlint.com/)

This tool simply validates a given JSON string. If I’m dealing with a small snippet of JSON that I have to process, I’ll drop it into the given window, which will neatly validate and format the code. Reading unformatted JSON outputs is a pain; don’t do it. Use a tool such as this to clean it up, so you can see what’s going on.

Json Editor (http://jsoneditor.net/)

When the JSON gets a little more complicated, pull out this tool. JSON editor lets you see the data in a tree format, which is useful when writing code to parse the JSON output on the fly. In addition, its a Json Editor, meaning that, if necessary, you can write up your own edits to the JSON and get that back as a revised JSON file.

Developers, what are you favorite tools for dealing with JSON? Do you use IDE plugins? Online site? Emacs? Let us know in the comments below or via twitter @droidweb

Implement a SwipeView in Android

Android development is partially about having a set of tools in your UI toolbox that you bring out when appropriate in the design and implementation phases of the project.  I’m about to add an invaluable tool to your toolbox.  Meet the SwipeView.

What is a “SwipeView”?

A SwipeView is an Android UI view similar to the homescreens.  You have several similar panes of content that you access by swiping left and right.  As you swipe left and right, transitions between the views are animated so that the view in focus follows your finger.  See the handy illustration below (Click to enlarge):

 

When Should I use a “SwipeView”?

SwipeViews are useful if you’re going to have several screens with the same layout and function that you want the user to switch between.  If you’ve ever used the Epicurious app they make good use of a SwipeView-esque implementation when searching for recipes.  Think of SwipeViews as something like a Gallery implementation for Views instead of just images.

How Do I implement a “SwipeView”?

Here’s the fun part.  Now that you know you want a SwipeView in your Android application how do you implement it.  As you probably know its not a standard Android View.  As such we’re going to make use of a third party library.  Jason Fry has put together a nice library for the simple implementation of SwipeViews.  Head on over to his site and blog post for more details about how to implement your very own SwipeView.  Since each SwipeView implementation is going to be widely different, I’m just going to summarize the steps to implement his library below:

  • Add SwipeView element (<uk.co.jasonfry.android.tools.ui.SwipeView…) to the desired XML layout as you would any Android View.
  • Reference SwipeView in java code via findViewById() as usual
  • Populate SwipeView with number of views that you’d like to be able to swipe between
  • Implement method private class SwipeImageLoader implements OnPageChangedListener {public void onPageChanged(int oldPage, int newPage) {}}. Look at the library’s documentation and examples for more details on how to do this.  Essentially this method will handle dynamically allocating and populating views as your user swipes back and forth.

I would include an example of implementation here, but my implementation was quite unorthodox and borrowed ideas from how to implement ListViews and other portions of my Android experience. Needless to say its a bit more involved than what should be expected from an introduction to an UI pattern.  If you’d like help implementing your own SwipeView, feel free to drop a line in the comments below or give us a shoutout via twitter @droidweb.

Android Development Made Simpler with Droid-fu

,

When you program for Android you find yourself doing some of the same tasks repeatedly. As a programmer you know what I mean; how many times have you downloaded images from the Internet dynamically for use in an application?  How about extended a List Activity to show a list of items? And if I had a dollar for everytime I had to parse an xml file…

Now there’s an easy way to do some of the most common tasks in Android (and do them correctly!). Recently I stumbled upon Droid-fu, a library for some of Android’s most common task.  Just add the .jar file to your Android project and you’re ready to impement the snippets provided to you by Droid-fu.

What sort of things can you do with Droid-fu?  Glad you asked.  Currently the library has classes for:

  • Easy implementation of the dreaded AsyncTask
  • Context implementation including simple handles for resuming, restarting, and gracefully pausing your actvity
  • Dialog helpers
  • Management (including caching!) of web images
  • Easy use of the Gallery View
  • … much more.  For a complete overview check the Droid-fu API

I will be using this in some of my upcoming projects so expect to hear more about this library on this blog.  For now, check out the developer’s website and read up on what he’s up to.

Introduction to Android Application Development Part 4: Navigating the Eclipse IDE

Ok, now that you’ve go the SDK installed, its time to get familiar with the Eclipse IDE.  To help you with that I’ve prepared a short video in which I go through the eclipse IDE, point out a few things, and click a few others.

In the next post, we’ll create our application!

Introduction to Android Application Development Part 3: Installing Android 2.0 SDK on a Mac

Here’s a repost of an earlier blog post for everyone at the Humanities Gaming Institute.

Lately I’ve updated to Android 2.0 SDK.  In the process I noticed that things were slightly different.  Following my motto of “Scratching my head so you don’t have to,” I’ve decided to document the new process of installing the SDK from scratch.  (And I mean from scratch… I just freshly installed Mac OSX yesterday.)

System Details:
Here are some details on my system so you know what environment I’m working in:

Picture 1

Essentially I’m running a white MacBook about a year and a half old… Theoretically this install should work with any Mac.

Step 1: Get Eclipse
If you already have eclipse feel free to skip this step, but I was serious about documenting the process from scratch…

Download the version of Eclipse for your purposes at http://www.eclipse.org/downloads/.  I download the Eclipse IDE for Java Developers because I mostly use Eclipse for Android development.  Under this header I choose the Mac Cocoa 32 bit download, as the Carbon download is soon to be deprecated.

Picture 2

Unzip the downloded tar.gz file somewhere convenient.  I just unzipped it to my ‘Documents’ folder.  Inside this folder there is an eclipse executable with the familiar eclipse logo.  (I just add eclipse to my dock items afterwards so I don’t have to hunt for it again.
Picture 3
Step 2: Download the Android SDK

Grab the Android SDK from the Android website.  Choose the proper SDK for your environment (which would be Mac OSX) and download.  Unzip this to an appropriate place as well.  Again I just dump it to my documents folder.

Step 3: (Optional but highly recommended) Add /tools to you $PATH variable

Now to make your life easier if you ever plan on doing anything remotely involved with android, add the /tools directory within the SDK folder to your $PATH variable.  This allows you to easily invoke the tools found in the folder, such as adb quickly from a terminal window.
To edit your path variable:

  1. Open a terminal window
  2. Edit your .bash_profile file (its ok if this doesn’t exist yet.  I just edit by nano .bash_profile
    )
  3. Add export PATH=${PATH}:<your_sdk_dir>/tools to the open file.  I usually make sure i get this right by popping open another terminal window and cd-ing until I’m in the /tools directory, typing pwd and copying and pasting the results.  My .bash_profile file now reads: export PATH=${PATH}:/Users/myusername/Documents/android-sdk-mac/tools
  4. Save and close.  To do this with nano use <ctrl>+<x> , <y>, <enter>
  5. To test whether your $PATH variable has changed, close all terminal windows, open a new one and type in $PATH.  Something like -bash: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Users/usernamehere/Documents/android-sdk-mac/tools: No such file or directory should appear.

Step 4: Install the Eclipse Plugin
Now we have to install the Eclipse plugin for Android development

  1. Open Eclipse
  2. Goto Help > Install New Software
  3. Click Add
  4. In the resulting popup box type Android ADT Plugin (or something similar) into the name field
  5. Type https://dl-ssl.google.com/android/eclipse/ into the Location field
  6. Press OK
  7. Check the box next to ‘Developer Tools’Picture 4
  8. Click Next.
  9. Accept the liscense agreememts
  10. Click Finish

At this point, the plugin should install.  After installation Eclipse will prompt you to restart it.

Step 5: Adding SDK Components
Here’s where things are different.  Instead of installing the SDK for a given version of Android, we now install SDK Components for that version of Android.  This allows us to test against many different versions of Android easily and make sure that that prized application we’ve worked on for the past several months works on Android 1.5, 1.6, 2.0, and over 9,000

  1. Open the preferences pane.  This can be done easily by the keyboard shortcut <cmnd> + <,>.
  2. Click Android on the left pane as shown below
    Picture 5
  3. In the field SDK Location fill in the directory where you unzipped the SDK
  4. Click Apply then Ok
  5. Go to Window > Android SDK and AVD Manager
    Picture 6
  6. Goto Available Packages, check the box next to the website listed, and check the components you want to install.  Click Install Selected. Accept all and Install. This will be how you install new Android versions.

Now you should be ready to go and start developing Android applications!  If you have any trouble following anything listed above, leave a comment and I’ll help remedy the situation.