Android Core

Android JSON Parsing with Gson Revisited

A while ago we hosted an article about using Gson for JSON parsing with Android. The tutorial was a simple showcase of how to leverage Gson with Android.

Recently, Bill Mote from the AYDABTU Development site contacted me and informed me that he had used our sample code in one of his Android applications, namely Broadcast SMS. More specifically, he refined and improved the initial version in order to create a more robust parser.

Let’s here what he has to say about his experience.

I was in the midst of writing my first Android application and I wanted to make my app “phone home” to accomplish a few things:

1. I wanted it to display a Message Of The Day (MOTD) to inform my customers of relevant information or to simply say thank you for their support occasionally,
2. I wanted it to present a list of features available in newer releases than is currently installed by any given user and provide them a vehicle for upgrading and
3. I wanted to set a low-water mark to disable older versions of the application.

A JSON web service seemed like the natural solution for this, but as I mentioned above, “I was writing my FIRST Android app.” ;)

I stumbled upon your Android JSON parsing with GSON article. What a wonderful and timely find! I know the article was simply intended to get the user started. Almost all articles are written this way. I want to give something back so I’ve taken your original article and expounded on it by hardening the HTTP request and the actual parsing of the JSON. I’ve also made the entire thing run in an AsyncTask (background thread) to get it off the UI thread as any kind of network hiccup or a large JSON string could cause the UI to become unresponsive and generate an error.

The full-on Try/Catch code can be found here: JSON Parsing Full Try-Catch.

Improvements:

* Runs as an AsyncTask to get it off the UI thread
* Handles socket/network timeouts
* Handles 404 errors
* Handles JSON syntax errors

Of note:

  • Anything that can throw an exception has been surrounded by a try/catch block and the application has been built to handle a null return.
  • I implemented an onStop() method to cancel the AsyncTask if the application should terminate as creating more than 1 AsyncTask will cause a force close.
  • Notice that we check for ‘this.isCancelled()’ before we finish the doInBackground() method — You can force this by starting the application and hitting the back button quickly.
  • You could grab the appropriate failure (aka catch()) and make the application retry on some period but that’s outside the scope of this example.

So, after making this run in a background thread and creating all those layers of try/catch complexity it occurred to me that I don’t care why it failed. I just need to account for it. I talked this over with a friend of mine that has much more development experience and he agreed with my basic idea: wrap the basic functions with a try/catch block and account for it, but remove all the layers. That includes removing the HTTP status response because in this case we don’t care if it failed. We’re either going to see the list of names or we’re not.

The simplified try-catch version of this code works in exactly the same way, but it’s less smart about why it had a problem. It can be found here: JSON Parsing Simplified Try-Catch.

My app, Broadcast SMS, has benefited from numerous on-line examples and tutorials. JavaCodeGeeks article helped me implement a JSON string parser that is working perfectly. Many thanks to them and all those that publish their works for the masses. I hope you find my enhancements useful.

Very nice, the enhancements helped create a more robust and less error-prone application. Thank you Bill. If you also have any improvements or additions you would like to contribute, please let shoot us an e-mail. Cheers!

Related Articles :

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Androidbloke Blogger
12 years ago

I can’t seem to get this working.  There seems to also be a new button that’s been introduced. Can I get a link to the full eclipse project? It would really clear things up!

Michael Weber
Michael Weber
12 years ago

Great improvement! But it can be implemented more generally. Basically its just important whether there is a JSONObject or a JSONArray to deserialze. So I could create a general JSONHelper including this two methods: private Collection deserializeJSONArray(InputStream source, Collection results) { Reader reader = new InputStreamReader(source); try { Type tokenType = new TypeToken<Collection>() { }.getType(); Collection response = this.gson.fromJson(reader, tokenType); results.addAll(response); } catch (JsonSyntaxException e) { Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e); } catch (JsonIOException e) { Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e); } finally { try { reader.close(); return results; } catch (IOException e) { Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e); } } return Collections.emptyList(); } private T… Read more »

Back to top button