Best coding practices in Android Part 1

By | December 29, 2017

Following conventions.

Do not try to create a new convention for coding. Follow the standard convention.
Like

  • Class Naming.
  • File Naming.
  • Variable Naming.
  • Code commenting.
  • Code intending.

Use Memory Efficient Structures

Map<Integer, String> map = new HashMap<Integer, String>();

The above code results in unnecessary Integer objects created.

Android provides data structures which are more efficient for mapping values to other objects. This reduces the garbage collection.
The table give examples for SparseArrays.

Below are the Efficient memory structures Android provides

SparseArray<E>

Maps integers to Objects, avoid the creation of Integer objects.

SparseBooleanArray

Maps integers to booleans.

SparseIntArray

Maps integers to integers

Use like this

SparseArray<String> map = new SparseArray<String>();
map.put(1, "Coderz Heaven");

Performing Background Jobs

  • Use Asynctasks and Services for long running Tasks. While normal services run in main thread as the application, it should be used to run very long tasks as it may slow down your application.
  • Asynctasks should be used for only short running tasks. You should look for configuration change such as Device Rotation.
  • while using Asynctasks. You can run Asynctasks in Series or Parallel.

Security and Privacy of Applications.

  • Use internal storage rather than external for storing applications files
  • Use Secure connections when connecting to the web
  • Make sure

etc

Better Loops for Better perfomance

There are several alternatives for iterating through an array:

static class Foo {
    int mSplat;
}

Foo[] mArray = ...

public void zero() {
    int sum = 0;
    for (int i = 0; i < mArray.length; ++i) {
        sum += mArray[i].mSplat;
    }
}

public void one() {
    int sum = 0;
    Foo[] localArray = mArray;
    int len = localArray.length;

    for (int i = 0; i < len; ++i) {
        sum += localArray[i].mSplat;
    }
}

public void two() {
    int sum = 0;
    for (Foo a : mArray) {
        sum += a.mSplat;
    }
}

zero() is slowest, because the JIT can’t yet optimize away the cost of getting the array length once for every iteration through the loop.

one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.

two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.

So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.

Avoid Creating Unnecessary Objects

Object creation is never free. A generational garbage collector with per-thread allocation pools for temporary objects can make allocation cheaper, but allocating memory is always more expensive than not allocating memory.
As you allocate more objects in your app, you will force a periodic garbage collection, creating little “hiccups” in the user experience. Thus, you should avoid creating object instances you don’t need to. Some examples of things that can help:

If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, instead of creating a short-lived temporary object.
When extracting strings from a set of input data, try to return a substring of the original data, instead of creating a copy. You will create a new String object, but it will share the char[] with the data.

An array of ints is a much better than an array of Integer objects, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.
If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.
Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience.

Try using Static Objects

If you don’t need to access an object’s fields, make your method static. Invocations will be about 15%-20% faster. It’s also good practice, because you can tell from the method signature that calling the method can’t alter the object’s state.

Use Static Final For Constants

Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";

The compiler generates a class initializer method, called , that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the “final” keyword:

static final int intVal = 42;
static final String strVal = "Hello, world!";


Avoid Internal Getters/Setters

Avoid Calling Getters and Setters inside the same Class.

The class no longer requires a method, because the constants go into static field initializers in the dex file. Code that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive “string constant” instruction instead of a field lookup.

Avoid Using Floating-Point>

As a rule of thumb, floating-point is about 2x slower than integer on Android-powered devices.

Beware of using Libraries

Make sure the external libraries you use in application only requires needed permissions and are not causing performance degradation.

Use Proper Input types for EditTexts.

Every text field expects a certain type of text input, such as an email address, phone number, or just plain text. So it’s important that you specify the input type for each text field in your app so the system displays the appropriate soft input method.

Example for Phone textbox..

<EditText
    android:id="@+id/phone"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/phone_hint"
    android:inputType="phone" />

Try using Android Studio

  • Android Studio uses the Gradle build system. Gradle has features like support for Maven repositories, multiple build types, multiple app flavors (for eg., demo & paid), apk splits (by screen density or ABI) & custom apk signing configurations.
  • Contains built-in 9-patch creator.
  • You can view previews for drawables, strings, colors & other resources.
  • A color picker to pick colors in layouts and drawables.
  • Almost all navigation & keyboard shortcuts

You can find the rest of the tips in my second article..

One thought on “Best coding practices in Android Part 1

  1. Pingback: Best Coding Practices in Android – Part 2 – CoderzHeaven

Leave a Reply

Your email address will not be published. Required fields are marked *