You can find the first part of this article here

Automatic code formatting and import organizing

Code styling is important. A well formatted piece of code becomes more readable and more comprehensible.

But sometimes trying to keep the code formatted can be negative: you lose your time and your focus. You will soon start to count the number of spaces at the beginning of the current line, or you will think about questions like “should I use 2 or 4 spaces for tabs?” or “should I put a space before this bracket?” or again “lets remove some unused imports because my IDE is saying that I’m not using them”, and you will lose your focus on that great algorithm that sits in your mind waiting to become the core of a great application. Then you have to spend some other time trying to get to the point, and restart writing code.

I think that it’s better to leave all the annoying stuff about code formatting to your IDE. Every modern IDE has an automatic formatting function, that can be triggered automatically when the file is saved or when it’s committed. And the same functionality exists for automatic imports organizing.

Eclipse

  • Settings: Java -> Code style -> Formatter
  • Auto format code: CTRL + SHIFT + F
  • Auto organize imports: CTRL + SHIFT + O

Android Studio

  • Settings: Code style -> Formatter -> Java
  • Auto format code: CTRL + ALT + L
  • Auto organize imports: CTRL + ALT + O

With Android Studio I prefer to let the IDE reformat my code before committing, as you can see in the following screenshot: Android Studio commit dialog

When you’re writing code, think about writing code, no matter how beautiful it is. You can think about formatting later, or even don’t think about formatting at all because your IDE will do it for you. But also don’t forget to produce well formatted code!

Bonus: don’t waste your time formatting JSON strings or long SQL queries! Ask Google for “json formatter” or “sql formatter”, and try some online time-saving tools.

Online tools for code generation

Talkin’ about boilerplate code, you can find many tools that will take care to generate code for you. This leads to time saving, less annoyances, and (most important) less bugs.

Here are some tools that I love to use in my activity as Android developer:

Do you know some other useful tool? Don’t forget to write a comment about it!

Again, don’t waste your time coding! Type just what you need to type, you’ll become more productive and less stressed.

Access Storage Framework and the URI permissions nightmare

I’ve been working with the Access Storage Framework introduced with Android KitKat, a feature that I’ve been waiting for a long time.

Everything seemed to be alright, quite easy to implement, until I faced a strange issue.

Once the file has been selected by the user, I wanted to store the file’s URI and re-open that URI the next time application is started. To do this, I’ve followed what the official documentation says:

When your app opens a file for reading or writing, the system gives your app a URI permission grant for that file. It lasts until the user’s device restarts. But suppose your app is an image-editing app, and you want users to be able to access the last 5 images they edited, directly from your app. If the user’s device has restarted, you’d have to send the user back to the system picker to find the files, which is obviously not ideal.

To prevent this from happening, you can persist the permissions the system gives your app. Effectively, your app “takes” the persistable URI permission grant that the system is offering. This gives the user continued access to the files through your app, even if the device has been restarted:

final int takeFlags = intent.getFlags()
            & (Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(uri, takeFlags);

It didn’t work. Doh!

I was getting a

1
java.lang.SecurityException
while trying to open the URI using
1
getContentResolver().openInputStream(uri)
or
1
getContentResolver().openAssetFileDescriptor(uri, "r")
:

java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{430b1748 4572:com.x.x.7/u0a88} (pid=4572, uid=10078) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS

Adding

1
android.permission.MANAGE_DOCUMENTS
to AndroidManifest.xml didn’t helped, and the many solutions found on stackoverflow.com didn’t work.

After taking a deeper look at the APIs and the source code I’ve found a working way to grant URI permissions:

activity.grantUriPermission(activity.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

place this call before

1
getContentResolver().takePersistableUriPermission(uri, takeFlags)
and read permissions will be granted! Yeah!

The resulting code will be:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == MY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
    if (data != null) {

      Uri uri = data.getData();

      mActivity.grantUriPermission(mActivity.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

      final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION);
      mActivity.getContentResolver().takePersistableUriPermission(uri, takeFlags);

      doSomethingWith(uri);
    }
  }
}

Life is too short: please, don’t waste your time writing code! I’m not saying that you don’t have to code, but many people tend to waste too much time typing on the keyboard instead of producing code. Mee too.

Following examples relate to Android’s world, but that can be easily adapted to other languages and programming tasks.

Aliases

Android developers, how many times do you have to call the command

1
adb
? If your installation directory is something like

1
/opt/android/sdk

maybe you’re going to write

1
/opt/android/sdk/platform-tools/adb
many many times a day.

Don’t do it! Instead add the android

1
/opt/android/sdk/platform-tools/
directory to your path or create an alias so you will only need to write
1
adb
!

I’ve also an alias for writing only

1
logcat
instead of
1
adb logcat
! ;-)

Some other alias examples:

# android
alias amstart='adb shell am start -n'
alias amkill='adb shell am kill'
alias media_scan='adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///mnt/sdcard'
alias packages='adb shell pm list packages'
alias install='ant debug install'
alias install='./gradlew installDebug'

# svn
alias svnlog='svn log | less'
alias svn_ignore_edit='svn propedit svn:ignore . --editor-cmd nano'

# git
alias revert='git checkout --'

Snippets and Templates

Every modern IDE has the support for snippets and templates.

Explore the built-in snippets and templates included in your IDE and use them as an example to write your own. You can create small blocks like a try/catch implementation or generate an entire class.

I’ve changed the default Android Studio template for try/catch block including exception logging. Go to File -> Settings -> File and Code Templates, select Catch Statement Body and change the default implementation with:

1
Log.d(TAG, "got exception", ${EXCEPTION});

If you use Robolectric you can change the default Junit4 Test Class implementation with the following, so annotations and basic imports are added automatically:

import static org.junit.Assert.*;
import static org.fest.assertions.api.Assertions.*;

import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class ${NAME} {
  ${BODY}
}

In Eclipse templates are under Preferences -> Java -> Code Style -> Code Templates and Preferences -> Java -> Editor -> Templates.

If you prefere Sublime Text you can find some useful Android Snippets in this repo: http://github.com/ribot/SublimeAndroidSnippets

Starting from this blog post by Bryan Rosenbaum, here is a gradle task to auto increment versionCode inside your build.gradle file.

import java.util.regex.Pattern

...

task incrementVersionCode << {
    println(":incrementVersionCode - Incrementing Version Code...")
    def buildGradleFile = file("build.gradle")
    def patternVersionCode = Pattern.compile("versionCode (\\d+)")
    def buildGradleFileText = buildGradleFile.getText()
    def matcherVersionCode = patternVersionCode.matcher(buildGradleFileText)
    matcherVersionCode.find()
    def mVersionCode = Integer.parseInt(matcherVersionCode.group(1))
    def mNextVersionCode = mVersionCode + 1
    def manifestContent = matcherVersionCode.replaceAll("versionCode " + mNextVersionCode)
    println(":incrementVersionCode - current versionCode=" + mVersionCode);
    println(":incrementVersionCode - next versionCode=" + mNextVersionCode);
    buildGradleFile.write(manifestContent)
}

Now run

1
gradle incrementVersionCode
and your build.gradle will be automatically updated.

There are many ways to create a fragment in Android, but to create a fragment properly you need to follow specific guidelines.

For example, it’s required that the class has a public zero-parameters constructor. If we need to pass parameters to the fragment, we need to use the method

1
setArguments()
.

Try to pass some parameters to the constructor as you do with any other class and then look at what happens after a device rotation: parameters will be lost. On screen rotation the fragment is automatically destroyed and re-created, and to do that Android uses the default constructor (public with no parameters). Nevertheless, the arguments will be saved and retrieved from the operating system if these have been set by the method

1
setArguments()
.

With the Android Fragment Code Generator tool you can generate in few seconds the necessary code to successfully implement a fragment, without having to worry too much of the aspects mentioned above.

Try it here: Android Fragment Code Generator