Introduction to Android Application Development, Fourth Edition (2014)
Part VI. Appendixes
D. Android IDE and Eclipse Tips and Tricks
The Android IDE (a special version of the Eclipse IDE with the ADT plugin preinstalled) is included as part of the Android ADT Bundle. The Android IDE (Eclipse) is one of the most popular development environments for Android developers. In this appendix, we provide a number of helpful tips and tricks for using the Android IDE to develop Android applications quickly and effectively. Even though you may choose to use your own copy of Eclipse and manually install the ADT plugin yourself, the instructions provided within this appendix apply to using either the Android IDE or Eclipse with ADT. Since the Android IDE and Eclipse with the ADT plugin are equivalent, from here on, we will refer only to the Android IDE.
Organizing Your Android IDE Workspace
In this section, we provide a number of tips and tricks to help you organize your Android IDE workspace for optimum Android development.
Integrating with Source Control Services
The Android IDE has the ability to integrate with many source control packages using add-ons or plugins. This allows the Android IDE to manage checking out a file (making it writable) when you start to edit it, checking a file in, updating a file, showing a file’s status, and a number of other tasks, depending on the support of the add-on.
Common source control add-ons are available for CVS, Subversion, Perforce, Git, Mercurial, and many other packages.
Generally speaking, not all files are suitable for source control. For Android projects, any file within the /bin and /gen directories shouldn’t be in source control. To exclude these generically within the Android IDE, go to Window, Preferences, Team, Ignored Resources. You can add file suffixes such as *.apk, *.ap_, and *.dex by clicking the Add Pattern... button and adding one at a time. Conveniently, this applies to all integrated source control systems.
Repositioning Tabs within Perspectives
The Android IDE provides some pretty decent layouts with the default perspectives. However, not everyone works the same way. We feel that some of the perspectives have poor default layouts for Android development and could use some improvement.
Experiment to find a tab layout that works well for you. Each perspective has its own layout, too, and the perspectives can be task oriented.
For instance, the Properties tab is usually found on the bottom of a perspective. For code, this works fine because this tab is only a few lines high. But for resource editing in Android, it doesn’t work so well. Luckily, in the Android IDE this is easy to fix: simply drag the tab by left-clicking and holding on the tab (the title) itself and dragging it to a new location, such as the vertical section on the right side of the Android IDE window. This provides the much-needed vertical space to see the dozens of properties often found here.
If you mess up a perspective or just want to start fresh, you can reset it by choosing Window, Reset Perspective.
Sometimes you might find that the editor window is just too small, especially with all the extra little metadata windows and tabs surrounding it. Try this: double-click the tab of the source file that you want to edit. Boom! It’s now nearly the full Android IDE window size! Double-click to return the window to normal. (Ctrl+M works on Windows, Command+M on the Mac.)
You can minimize entire sections, too. For instance, if you don’t need the section at the bottom that usually has the console or the one to the left that usually has the Package Explorer view, you can use the minimize button in each section’s upper-right corner. Use the button that looks like two little windows to restore it.
Viewing Windows Side by Side
Ever wish you could see two source files at once? Well, you can! Simply grab the tab for a source file and drag it either to the edge of the editor area or to the bottom. You will then see a dark outline (shown in Figure D.1) showing where the file will be docked—either side by side with another file or above or below another file. This creates a parallel editor area (shown in Figure D.2) where you can drag other file tabs as well. You can repeat this multiple times to show three, four, or more files at once.
Figure D.1 A dark outline indicating how the windows will appear when docked side by side.
Figure D.2 Two windows docked side by side.
Viewing Two Sections of the Same File
Ever wish you could see two places at once in the same source file? You can! Make sure the file is open and focused, select Window from the menu, then choose New Editor. A second editor tab for the same file comes up. With the previous tip, you can now have two different views of the same file (see Figure D.3).
Figure D.3 Viewing different sections of the same file in two different windows side by side.
Closing Unwanted Tabs
Ever feel like you have far too many tabs open for files you’re no longer editing? We do! There are a number of solutions to this problem. First, you can right-click a file tab and choose Close Others to close all other open files. You can quickly close specific tabs by middle-clicking each tab. (This even works on a Mac with a mouse that can middle-click, such as one with a scroll wheel.)
Keeping Windows under Control
Finally, you can use the Android IDE setting that limits the number of open file editors:
1. Open the Android IDE’s Preferences dialog.
2. Expand General, choose Editors, and check Close editors automatically.
3. Edit the value in Number of opened editors before closing.
This will cause old editor windows to be closed when new ones are opened. Eight seems to be a good number to use for the Number of opened editors before closing option to keep the clutter down but to have enough editors open to still get work done and have reference code open. Note also that if you select Open new editor under When all editors are dirty or pinned, more files will be open if you’re actively editing more than the number chosen. Thus, this setting doesn’t affect productivity when you’re editing a large number of files all at once but can keep things clean during most normal tasks.
Creating Custom Log Filters
Every Android log statement includes a tag. You can use these tags with filters defined in LogCat. To add a new filter, click the green plus sign button in the LogCat pane. Name the filter—perhaps using the tag name—and fill in the tag you want to use. Now there is another tab in LogCat that shows messages that contain this tag. In addition, you can create filters that display items by severity level.
Android convention has largely settled on creating tags based on the name of the class. You see this frequently in the code provided with this book. Note that we create a constant in each class with the same variable name to simplify each logging call. Here’s an example:
public static final String DEBUG_TAG = "MyClassName";
This convention isn’t a requirement, though. You could organize tags around specific tasks that span many activities, or you could use any other logical organization that works for your needs. Another simpler way to do this is as follows:
private final String DEBUG_TAG = getClass().getSimpleName();
Although not as efficient at runtime, this code can help you avoid copy-and-paste errors. If you’ve ever been looking over a log file and had a misnamed debug tag string mislead you, this trick may be useful to you.
Searching Your Project
You have several ways to easily search your project files from within the Android IDE. The search options are found under the Search menu of the Android IDE toolbar. Most frequently, we use the File search option, which allows you to search for text within the files found in the workspace, as well as for files by name. The Java search option can also help you find Java-specific elements of your project such as methods and fields.
Organizing Android IDE Tasks
By default, any comment that starts with // TODO will show up on the Tasks tab in the Java perspective. This can be helpful for tagging code areas that require further implementation. You can click a specific task and it will take you straight to the comment in the file so you can implement the item at a later time.
You can also create custom comment tags above and beyond to-do items. We often leave comments with people’s initials to make it easy for them to find specific functional areas of the application to code review. Here’s an example:
// LED: Does this look right to you?
// CDC: Related to Bug 1234. Can you fix this?
// SAC: This will have to be incremented for the next build
You might also use a special comment such as //HACK when you have to implement something that is less than ideal, to flag that code as subject to further review. To add custom tags to your Task list, edit your Android IDE preferences (available at Window, Preferences) and navigate to Java,Compiler, Task Tags. Add any tags you want to flag. The tags can be flagged for a certain priority level. So, for instance, something with your initials might be a high priority to look at right away, but a HACK flag may be a low priority because, presumably, it works but maybe not in the best way possible.
Writing Code in Java
In this section, we provide a number of tips and tricks to help you implement the code for your Android applications.
Autocomplete is a great feature that speeds up code entry. If this feature hasn’t appeared for you yet or has gone away, you can bring it up by pressing Ctrl+spacebar. Autocomplete not only saves time in typing but also can be used to jog your memory about methods—or to help you find a new method. You can scroll through all the methods of a class and even see the Javadocs associated with them. You can easily find static methods by using the class name or the instance variable name. You follow the class or variable name with a dot (and maybe Ctrl+spacebar) and then scroll through all the names. Then you can start typing the first part of a name to filter the results.
Creating New Classes and Methods
You can quickly create a new class and corresponding source file by right-clicking the package to create it and then choosing New, Class. Next, you enter the class Name, pick a Superclass and Interfaces, and choose whether to create default comments and method stubs for the superclass for constructors or abstract methods.
Along the same lines as creating new classes, you can quickly create method stubs by right-clicking a class or within a class in the editor and choosing Source, Override/Implement Methods. Then you choose the methods for which you’re creating stubs, where to create the stubs, and whether to generate default comment blocks.
When referencing a class in your code for the first time, you can hover over the newly used class name and choose Import “Classname” (package name) to have the Android IDE quickly add the proper import statement.
In addition, the Organize Imports command (Ctrl+Shift+O in Windows and Command+Shift+O on a Mac) causes the Android IDE to automatically organize your imports. The Android IDE removes unused imports and adds new ones for packages used but not already imported.
If there is any ambiguity in the name of a class during automatic import, such as with the Android Log class, the Android IDE prompts you for the package to import. Finally, you can configure the Android IDE to automatically organize the imports each time you save a file. This can be set for the entire workspace or for an individual project.
Configuring this for an individual project gives you more flexibility when you’re working on multiple projects and don’t want to make changes to some code, even if the changes are an improvement. To configure this, perform the following steps:
1. Right-click the project and choose Properties.
2. Expand Java Editor and choose Save Actions.
3. Check Enable project specific settings, check Perform the selected actions on save, and check Organize imports.
The Android IDE has a built-in mechanism for formatting Java code. Formatting code with a tool is useful for keeping the style consistent, applying a new style to old code, or matching styles with a different client or target (such as a book or an article).
To quickly format a small block of code, select the code and press Ctrl+Shift+F in Windows (or Command+Shift+F on a Mac). The code is formatted to the current settings. If no code is selected, the entire file is formatted. Occasionally, you need to select more code—such as an entire method—to get the indentation levels and brace matching correct.
The Android IDE formatting settings are found in the Properties pane under Java Code Style, Formatter. You can configure these settings on a per-project or workspace-wide basis. You can apply and modify dozens of rules to suit your own style.
Renaming Almost Anything
The Android IDE’s Rename tool is quite powerful. You can use it to rename variables, methods, class names, and more. Most often, you can simply right-click the item you want to rename and then choose Refactor, Rename. Alternatively, after selecting the item, you can press F2 in Windows (orCommand+Alt+R on a Mac) to begin the renaming process. If you are renaming a top-level class in a file, the filename has to be changed as well. The Android IDE usually handles the source control changes required to do this, if the file is being tracked by source control. If the Android IDE can determine that the item is in reference to the identically named item being renamed, all instances of the name are renamed as well. Occasionally, this even means comments are updated with the new name. Quite handy!
Do you find yourself writing a whole bunch of repeating sections of code that look, for instance, like the following?
TextView nameCol = new TextView(this);
This code sets text color, text size, and text. If you’ve written two or more blocks that look like this, your code could benefit from refactoring. The Android IDE provides two useful tools—Extract Local Variable and Extract Method—to speed this task and make it almost trivial.
Using the Extract Local Variable Tool
Follow these steps to use the Extract Local Variable tool:
1. Select the expression getResources().getColor(R.color.title_color).
2. Right-click and choose Refactor, Extract Local Variable (or press Alt+Shift+L).
3. In the dialog that appears, enter the Name for the variable and leave the Replace all occurrences check box selected. Then click OK and watch the magic happen.
4. Repeat Steps 1–3 for the text size.
The result should now look like this:
int textColor = getResources().getColor(R.color.title_color);
float textSize = getResources().getDimension(R.dimen.help_text_size);
TextView nameCol = new TextView(this);
All repeated sections of the last five lines also have this change made. How convenient is that?
Using the Extract Method Tool
Now you’re ready for the second tool. Follow these steps to use the Extract Method tool:
1. Select all five lines of the first block of code.
2. Right-click and choose Refactor, Extract Method (or choose Alt+Shift+M).
3. Name the method and then click OK and watch the magic happen.
By default, the new method is below your current one. If the other blocks of code are actually identical (meaning the statements of the other blocks are in the exact same order), the types are all the same, and so on, they will also be replaced with calls to this new method. You can see this in the count of additional occurrences shown in the dialog for the Extract Method tool. If that count doesn’t match what you expect, check that the code follows exactly the same pattern. Now you have code that looks like the following:
addTextToRowWithValues(newRow, scoreUserName, textColor, textSize);
It is easier to work with this code than with the original code, and it was created with almost no typing! If you had ten instances before refactoring, you’ve saved a lot of time by using a useful Android IDE feature.
Sometimes, formatting code isn’t enough to make it clean and readable. Over the course of developing a complex Activity, you might end up with a number of embedded classes and methods strewn about the file. A quick Android IDE trick comes to the rescue. With the file in question open, make sure the outline view is also visible.
Simply click and drag methods and classes around in the outline view to place them in a suitable logical order. Do you have a method that is called only from a certain class but is available to all? Just drag it into that class. This works with almost anything listed in the outline, including classes, methods, and variables.
The QuickFix feature, accessible under Edit, Quick Fix (or Ctrl+1 in Windows and Command+1 on a Mac), isn’t just for fixing possible issues. It brings up a menu of various tasks that can be performed on the highlighted code, and it shows what the change will look like. One useful QuickFixnow available is the Android Extract String command. Use QuickFix on a string literal and quickly move it into an Android string resource file, and the code is automatically updated to use the string resource. Consider how QuickFix Extract String would work on the following two lines:
Log.v(DEBUG_TAG, "Something happened");
String otherString = "This is a string literal.";
The updated Java code is shown here:
String otherString = getString(R.string.string_literal);
And these entries have been added to the string resource file:
<string name="something_happened">Something happened</string>
<string name="string_literal">This is a string literal.</string>
The process also brings up a dialog for customizing the string name and which alternative resource file it should appear in, if any.
The QuickFix feature can be used in layout files with many Android-specific options for performing tasks such as extracting styles, extracting pieces to an include file, wrapping pieces in a new container, and even changing the widget type.
Providing Javadoc-Style Documentation
Regular code comments are useful (when done right). Comments in Javadoc style appear in code completion dialogs and other places, thus making them even more useful. To quickly add a Javadoc comment to a method or class, simply press Alt+Shift+J in Windows (also Alt+Shift+J on a Mac). Alternatively, you can choose Source, Generate Element Comment to prefill certain fields in the Javadoc, such as parameter names and author, thus speeding the creation of this style of comment. Finally, if you simply start the comment block with /** and press Enter, the appropriate code block will be generated and prefilled as before.
Resolving Mysterious Build Errors
Occasionally, you might find that the Android IDE finds build errors where there were none just moments before. In such a situation, you can try a couple of quick Android IDE tricks.
First, try refreshing the project. Simply right-click the project and choose Refresh or press F5. If this doesn’t work, try deleting the R.java file, which you can find under the /gen directory under the name of the particular package being compiled. (Don’t worry; this file is created during every compile.) If the Compile Automatically option is enabled, the file is re-created. Otherwise, you need to compile the project again.
A second method for resolving certain build errors involves source control. If the project is managed by the Android IDE via the Team, Share Project menu selection, the Android IDE can manage files that are to be read-only or automatically generated. Alternatively, if you can’t or don’t want to use source control, make sure all of the files in the project are writable (that is, not read-only).
Finally, you can try cleaning the project. To do this, choose Project, Clean and choose the project(s) you want to clean. The Android IDE removes all temporary files and then rebuilds the project(s). If the project was an NDK project, don’t forget to recompile the native code.
In this appendix, you have learned useful tips and techniques for leveraging many powerful features provided with the Android IDE. You have learned quite a few tips for organizing your Android IDE workspace. You have also learned useful tricks for writing code for your applications in Java. The many features of the Android IDE (Eclipse) make this the best choice of IDE for developing Android applications.
1. True or false: It is possible to use source control from within the Android IDE.
2. What is the keyboard shortcut for maximizing windows within the Android IDE?
3. Describe how to view two source file windows at once.
4. True or false: It is not possible to view two different sections of the same file in two different windows within the Android IDE.
5. What is the keyboard shortcut for formatting Java code?
6. What is the keyboard shortcut for using the Extract Local Variable tool?
7. What is the keyboard shortcut for using QuickFix?
1. Practice using the various keyboard shortcuts mentioned throughout this appendix.
2. Use the Eclipse documentation or the Internet to discover at least one other useful keyboard shortcut for Java development not mentioned in this appendix.
3. Practice rearranging the various UI elements within the Android IDE until you are comfortable with your arrangement.
References and More Information
Eclipse Resources: “Eclipse Resources”:
Eclipse Resources: “Eclipse Documentation”:
Eclipse Resources: “Getting Started”:
Eclipse Wiki: “Main Page”:
Oracle Java SE Documentation: “How to Write Doc Comments for the Javadoc Tool”: