Home > Articles > Mobile Application Development & Programming

Simple Tips for Better Android Development

Ian G. Clifton, author of Essentials of Android Application Development LiveLessons, discusses some simple ways to improve the quality of your Android code immediately.
Like this article? We recommend

When you first begin developing or switch to a new platform, you’ll deal with a lot of unknowns. You can very easily make mistakes (despite good intentions) just because you aren’t aware of standard techniques and best practices. This article highlights a few things to consider when developing with Java, and for Android in particular.

Don’t Accept Null Unless Being Explicit

It doesn’t take long for a new Java developer to encounter his or her first NullPointerException. It is one of the most common causes of app crashes, despite the fact that it seems really easy to avoid. After all, just don’t use null when you need to have an object, right? Unfortunately, as a code base grows, it becomes more and more difficult to understand all the possible paths, so it can be unclear whether a reference is null or not. The situation becomes even more complex as multiple developers work on a project or third-party libraries are added.

You can’t always avoid having a null pointer handed around in code, but you can develop better coding practices to minimize the problem. In general, your methods shouldn’t take null as a parameter unless intentionally allowed. Consider this example:

public List<User> getUsers(int limit, Filter filter) {
    // ...
}

What happens when you pass in null for the Filter? You don’t know unless you dig into that code, which might pass off the null elsewhere, and that other place may or may not require it. You quickly get into a position where you actually don’t know what to expect; since you’re on a deadline, you make an assumption that it is (or isn’t) okay, and possibly you create a bug to bite you later. Now consider this same method with some changes:

/**
 * Returns a List of Users up to the specified limit
 *
 * @param limit int maximum number of users to return
 * @param optionalFilter Filter to further restrict results or null to just use the limit
 * @return List of Users requested, empty List if no results
 */
public List<User> getUsers(int limit, Filter optionalFilter){
  // ...
}

First, the comments explicitly say that null is okay. Even without the comments, the name of the parameter, optionalFilter, strongly implies that it can be null. As a bonus, you know that this method is intended never to return null, which means you can directly iterate over the result.

Use Annotations

One powerful feature of Java that is generally underutilized by new developers is annotations, which are basically metadata about code. Annotations can do virtually anything, such as preventing you from accidentally overriding methods, or even generating code for you. The power of annotations can be intimidating, so many developers avoid them altogether. If that’s you, force yourself to change; it won’t take long before you see the benefits.

A great way to start is with the easy-to-use @NonNull and @Nullable annotations from the Android support repository. If you’re using the support-v4 library or appcompat-v7, you’re ready to include the annotations. If not, make sure you have the Android Support Repository from the Android SDK Manager and then include the following in your Gradle dependencies:

compile 'com.android.support:support-annotations:21.0.3'

The @NonNull annotation means that the given parameter or return value cannot be null (or the app will crash), so Android Studio can warn you if you attempt to pass a null value where you shouldn’t. The @Nullable annotation means that the given parameter or return value can be null, letting Android Studio warn you if you try to use a value that might be null without checking (such as our previous optional filter). Our method could be updated to look like this:

@NonNull
public List<Object> getUsers(int limit, @Nullable Object optionalFilter) {
  // ...
}

This approach ensures that you cannot accidentally return null in this method and you don’t accidentally use the optionalFilter without checking for null first.

Some of the power of annotations comes when you start adding them all around your code and you can make quick guarantees about behavior. This technique will keep you from writing unnecessary null checks and help ensure that your code matches its contract.

One important note: You need to tell Android Studio to enforce these rules. Follow these steps:

  1. Open Settings and select Inspections on the left side (or type it in the search box at upper left).
  2. Go to Constant Conditions & Exceptions under Probable Bugs on the right (or search for it in the upper middle search box). Make sure that this option is checked.
  3. Click the Configure Annotations button. Make sure android.support.annotation.Nullable is in the top box and android.support.annotation.NonNull is in the bottom box (you can add them with the plus button). Click each of them, click the check button so that your generated code will include the annotations, and then click OK.
  4. I also recommend that you increase the Severity to Error to prevent you from building an app that ignores these annotations.

Don’t No-Op

A “no-op” (short for “no operation”) is a portion of code, such as a method, which does nothing in certain situations. One of the easiest ways to add difficult-to-troubleshoot bugs to your code is to see a NullPointerException in your logs, jump into that method, check whether the reference is null, and just return if it is. For instance, if the previous getUsers method required a Filter object, a poor solution would be to return null or an empty List if the Filter was null. The problem is that it’s easy to pass in null accidentally and then pass along the bad result to another method. Two weeks down the road you get crashes in your ListAdapter because it’s trying to get the size of a null List of Users. Now you have to backtrack through every method call that could lead to the display code, looking to find out how it could be empty, which could take hours. A no-op becomes a particular pain when it ends up affecting UI code, because that code is often triggered via the Looper (the class that handles Android’s message loop), so your stack trace won’t even include the methods that passed around the bad results.

Be Defensive

How do you handle the case of a method receiving null when it shouldn’t? Throw a NullPointerException! The idea of purposely throwing an exception often makes newer developers uneasy, because an exception can result in a crash. Crashes are bad for users, but they’re good for developers; they let you find out where something went wrong and fix it immediately. Instead of having the code in an inconsistent or unexpected state, a crash stops it from going forward. The earlier in the process that you throw an exception, the smaller the amount of code you’ll have to look through to find the problem. This is especially important if you’re writing any kind of interface code or a library to be used by other people. In that case, you really want to throw an exception the instant a method is called with any invalid parameters. Consider this updated version of the getUsers method:

public List<User> getUsers(int limit, Filter requiredFilter) {
   if (limit < 1) {
       throw new IllegalArgumentException("limit must be 1 or greater; received " + limit);
   }
   if (requiredFilter == null) {
       throw new NullPointerException("requiredFilter cannot be null");
   }
   // ...
}

Now it’s impossible for bad values to be passed to some other method. Any bad value results in a crash that calls out what was wrong. One of the most important things you can do with a throw like this is to give the actual value that was passed in, such as with the limit in this example. Without it, the developer only knows that some int less than one was passed in. With the actual value, the developer can see something like -2147483648 being returned, immediately knowing that Integer.MIN_VALUE was used by accident somewhere. It is pretty common to see the actual value and immediately realize what went wrong (for example, autocompleting the wrong constant).

Learn the Libraries

Android has been around long enough now that a lot of great libraries have been created, so you don’t need to reinvent the wheel. Any time you come across a challenge that you know must have been solved somewhere, take some time to look online for a library that handles that problem. You’ll save yourself a lot of work (and probably quite a few bugs); plus, you will probably learn more about development techniques and the Android community in the process.

If you’re not sure where to start, look at the Square libraries on GitHub. For example, the early days of Android necessitated that every app have its own HTTP layer, which would easily be thousands of lines of complex code to handle threading, callbacks, errors, and so on. Now, you can just use Square’s OkHttp library to make web requests with just a few lines of code. That library also is likely more efficient and better tested than what you’d write from scratch. If the web requests are just for using REST services, take a look at Retrofit.

In a lot of cases, multiple libraries are available that can be used for a given problem. For example, downloading images can be handled by another Square library called Picasso, Google’s Volley, or any one of many other libraries. Which one you use is up to you. Generally, you should look at the library’s API, documentation, when it was last updated, and a small sample of the code (you can usually spot red flags in bad libraries quite quickly). Another good idea is to do a quick search about that library to see what other developers are saying about it. When you take advantage of existing libraries, you can focus more on writing the code that is unique to your app, making it better and more reliable.

Wrapping Up

Most of the tips I’ve discussed in this article are about making your code predictable. Whether another developer is integrating your code today, or you’re providing an update to your own code six months from now, you’ll avoid a lot of common bugs by having made it obvious exactly how your code works and what values are allowed. Adding good comments, using clear argument names, including annotations, and throwing exceptions instead of silently accepting bad values will save you far more effort in the long run than the little bit of extra work those tasks take up front. On top of all that, taking advantage of quality libraries means that you don’t create new bugs by writing code for features that are readily available and already well tested.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020