Prasham Trivedi

Supercharge your Android Application-3(Data).

January 03, 2015

3 minutes to read.

part-1 is covering about list and list fragment while part-2 was all about view optimisations. In this part we will see how to work around with your data, mostly JSONs and working with databases. We will also see some other tips to supercharge our apps and development. So continuing the trend our tip#4 is.

4. Don't force, adjust.

Xmls from webservice are days long forgotten. We mostly use json for parsing data in our websevices. Even I have not got any xml response from webservice for ~2 years. And while working with Json sometimes our parsing stops execution at some random point, or crashes. While debugging it turns out that the key we want is not available in webservice response, which can be fairly normal given the conditions. What do we usually do in such situations? write try-catch?.

Before writing a try-catch block check your code. Do you write get...() methods to parse your json? If yes you don’t have to write try catch. Just change all of your get...() calls to opt...() calls, and you are crash free.

If you see the source code of JSONObject you can easily compare codes of get() method and opt() method. Both of them want to get the value of the key we have passed in argument. If this value is not found, get() throws JSONException while opt() returns silently. Here is the code from AOSP itself.

/**
 * Returns the value mapped by {@code name}.
 *
 * @throws JSONException if no such mapping exists.
*/
public Object get(String name) throws JSONException {
	Object result = nameValuePairs.get(name);
    if (result == null) {
        throw new JSONException("No value for " + name);
    }
    return result;
}
/**
 * Returns the value mapped by {@code name}, or null if no such mapping
 * exists.
*/
public Object opt(String name) {
	return nameValuePairs.get(name);
}

Thus, if you use opt...() calls instead of get...() calls, you will never face JSONException. Instead you will be returned with default values (0 or false depends on primitive types, and null when string).

Keep in mind while getting with JSONObject or JSONArray with opt calls proceed with parsing only if they are not null, or you may face NullPointerException when parsing.

5. Some tips about the database.

This section is not about big gotchas, but it’s about some smaller tips. Like

  1. While inserting and updating data, use `insert()` and `update()` methods. Unlike rawQuery method both of these will return some value indicating success or failure of your operations.
  2. If you are checking whether such record exists or not, it's desirable to call `cursor.moveToFirst()` instead of `cursor.getCount()`. In my observations getCount method is not as accurate as moveToFirst.
  3. Don't use `PRIMARY KEY AUTOINCREMENT` in all the cases. In most of the cases `PRIMARY KEY` is sufficient to increment all the values. If you use `AUTOINCREMENT` keyword, your last index is always saved in sqlite_sequence table, and when inserting a new value, it's index will always be your last index+1. (For Example: If you enter 10 values and than delete all rows, the next row you will insert will have id of 11 instead of 1 because of `AUTOINCREMENT`)
  4. In upgrade database logic, don't fire all queries at once, specially `ALTER TABLE` queries, try to run them one by one.
  5. Sometimes queries with arguments (like `where mycolumn=?`) may fail. Espacially when `mycolumn`'s data type differs from what you type in argument. In such case I usually change query with `where mycolumn=checkVal` and it works.

6. About handling your data in views and in debug.

This section is about handling your data in views and with debugging.

  1. TextUtils class is an angel, there are many methods I use in my daily work but there is one method which is Must Use for us. `TextUtils.isEmpty()` which will returns true if your string is empty or blank. Always use to save your self from `NullPointerException`. I promise there will be a post on TextUtils just because it's an angel for all of us.
  2. `toString()` method is another friend. I override this method in my object and return some crucial info about this instance. It helps me most when debugging or logging. I recommend you should use it too.

That’s it. In a final (and probably shortest) part of the series. We will check how to handle networks and other threading gotchas I have learned.

comments powered by Disqus