views:

2003

answers:

7

Please Help me compile a list of Effective Android Programming techniques

  1. Don't forget to free resources after use.
    Lot of resources like Cursors are overlooked. Free them too.

  2. Don't Use magic Numbers.
    values[0] is meaningless. The framework provides very useful accessors like values[SensorManager.DATA_X]


  1. "Make use of onPause()/onResume to save or close what does not need to be opened the whole time."

    protected void onResume() {
    mSensorManager.registerListener(...);
    }
    protected void onStop() {
      mSensorManager.unregisterListener(...);
      super.onStop();
    }
    
  2. Make your Android UI Fast and Efficient from the Google I/O has a lot of useful UI Performance tips.

+4  A: 
  • Close resources (files/streams, ...) after you do not need them any more
  • Override onDestroy() to clean up everything
  • Make use of onPause()/onResume to save or close what does not need to be opened the whole time.
Fernando Miguélez
Thanks for the last tip.
kunjaan
Can you give examples of resources that should be freed/recreated in `onPause()`/`onResume()`? I always find myself wanting to use those, but I can't find what for. For example: sqlite databases and cursors. Should these be closed when the app is paused? I close them when it's destroyed, in hopes that resuming the app is quicker.
Felix
I added a code snippet of an example. Please tell me if I am wrong.
kunjaan
+17  A: 

Designing for Performance covers:

  • Optimize Judiciously
  • Avoid Creating Objects
  • Performance Myths
  • Prefer Static Over Virtual
  • Avoid Internal Getters/Setters
  • Use Static Final For Constants
  • Use Enhanced For Loop Syntax
  • Avoid Enums Where You Only Need Ints
  • Use Package Scope with Inner Classes
  • Use Floating-Point Judiciously
  • Know And Use The Libraries
  • Use Native Methods Judiciously

Best Practices for User Interfaces:

1 Read the UI guidelines

2 Understand and design for touch mode

3 But, support multiple interaction modes

4 Use notifications and the window shade

5 Support interaction between applications

6 Keep your UI fast and responsive

7 Use widgets and live folders

8 Handle screen orientation changes

9 Use images wisely

10 Use layouts that adapt to multiple devices

And from SO:

Android: Best practice for responsive user interfaces

Best practices for unit testing Android apps

DOK
Awesome List. It would be awesome if you wrote a small snippet on tips like "Use Images Wisely" etc. Thank you very much.
kunjaan
Well, adding code snippets would make my answer awfully long. That's why I provided links.
DOK
+1 Awesome list. I'll have to keep it around in case I start developing for Android. I wish we could somehow pin this question (or increase it's importance) as a good starting place for android devs.
Evan Plaice
+10  A: 

Might be a too personal opinion, and more related to app design rather than programming, but here goes:

Don't copy UI paradigms from other platforms (especially the iPhone)

I've seen quite a few apps that try to copy the "footer" that many iPhone apps have (iPhone - Android). I'm strongly against that -- it looks out of place as it is not native to the platform and it wastes screen real estate. Instead, use the MENU button (it's there for a reason). Worst case scenario use a TabHost (still wastes some space but at least it's native to the platform and the user will get a consistent look).

Felix
I agree, UI paradigms need to be integrated seamless into the platform following the the platform paradigms.
Moss
+4  A: 
  1. DalvikVM Garbage Collector calls are expensive. They can lockup the UI thread easily. If you want smooth scrolling you should avoid creating too many objects. Prefer the reuse of existing objects and not creating new ones. You can analyze your object creation statistics with the "Allocation Tracker" tab in the Eclipse DDMS perspective.

  2. Starting a new thread is expensive. Use one thread that executes required tasks one by one, or use thread pools. You should use built in classes like AsyncTask whenever possible.

  3. If your data set gets relatively large (>100KB) don't store it in text file or XML file - parsing it will be too expensive. Use the native SQLite implementation instead.

  4. Eclipse MAT is a great tool to analyze memory allocations. It will help to find memory leaks in your application.

Fedor
+4  A: 

Always prepare and launch intents from a separate method and name those methods consistently. The code to launch an intent usually requires minor changes and parameter tweaks as the project progresses. It changes frequently, and often all the intent code is looked at together. Mixing it in next to other code causes nothing put lingering, hard to debug, headaches.

So instead of what is shown in the Notepad tutorial (part 2) fragment for OnListItemClick():

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Cursor c = mNotesCursor;
    c.moveToPosition(position);
    Intent i = new Intent(this, NoteEdit.class);
    i.putExtra(NotesDbAdapter.KEY_ROWID, id);
    i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(c
            .getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
    i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(c
            .getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
    startActivityForResult(i, ACTIVITY_EDIT);
}

Do this instead:

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      Cursor c = mNotesCursor;
      c.moveToPosition(position);
      intent_edit_for_result(id, c.getString(
           c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)),
           c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));     
 }

 protected intent_edit_for_result(long, rowId, String title, String body) {
      Intent i = new Intent(this, NoteEdit.class);
      i.putExtra(NotesDbAdapter.KEY_ROWID, rowId);
      i.putExtra(NotesDbAdapter.KEY_TITLE, title );
      i.putExtra(NotesDbAdapter.KEY_BODY, body );
      startActivityForResult(i, ACTIVITY_EDIT);
 }

The performance cost is minimal, mistakes are easier to see, testing is easier, and you won't cringe when need to review all your intent related code.

Charles Merriam
+31  A: 

Here's my personal top twenty. I use this in addition to the usual lists from d.android.com. I could add another five, though the list is long enough.

  1. Add Two Numbers: Your first non-tutorial application should be to take two numbers and add them together. It sounds too simple. You will spend some hours getting the layouts, the callbacks, and onPause/onResume to work correctly. Do it.
  2. It is Java: You work in Java for most of your Android programming. Don't spend time praising it. Don't spend time complaining about it. Just work with it.
  3. Love RelativeLayout: Most of the tutorials use LinearLayout, but you will find that RelativeLayout is truly useful. Many layouts, like the GridLayout aren't used much at all. Play around with RelativeLayout. See an example from this question.
  4. Use fill_parent with a top level RelativeLayout: A surprisingly common and hard to find problem is putting a wrap_content in a top level RelativeLayout and then wondering why unrelated fields far down in the hierarchy are rendering strangely.
  5. Use empty layout items: You will often use empty items in your layouts just for positioning other layouts. For example, you might use an empty TextField, of width=0 and height=0 and centerInParent='True' just to anchor things relative to the middle of the screen. Also, you might have an empty TextField or LinearLayout so that you can give a layout_weight=1 to it and have it take up more screen space.
  6. Set a layout background color: If you are having trouble figuring out your layout, try setting the background colors on some objects. It can highlight your mistakes faster than other tools, and shows some surprises that the IDE red box doesn't always help.
  7. Download Apps-For-Android: This is a big chunk of useful source code for a half dozen applications. It can supplement the sample applications nicely and show different coding style solutions. Grab it using svn http://apps-for-android.googlecode.com/svn/trunk/ apps-for-android-read-only
  8. Download the source: You need the Android source to solve some problems or, more likely, get past holes in the documentation. Your copy does not need to perfect or kept up to date. You can learn to use the repo command, or just visit http://bit.ly/biOLUt for snapshot.
  9. Learn to search your source: The fastest solution to many problems is to find where a particular parameter is used in some other source. Put a copy or link to the sample applications, apps-for-android applications, and any other source you have under one directory tree. Use "grep -ir funky_parameter sample_code/" or your favorite searching routine to quickly find some code that uses that parameter.
  10. Use Eclipse: Even you have a favorite editor or IDE you have used for years, use Eclipse for Android development. It is good enough as an IDE and is really part of the development tools suite. Any time you spend trying to jury-rig your IDE to work is time you didn't code.
  11. Learn Eclipse: Learn a few new tricks with Eclipse every day. Some of my favorite commands were found reading this list and this question.
  12. Get help when starting out: The quantity of readable material can be overwhelming. Setting up the environment can be tricky. Going to an Android Meet-up or users group can help get over the initial hump.
  13. Code every day: Android code will be frustrating. Don't allow yourself to stop because you get stuck. Play around with the tools, step through a sample application, read one of the articles, or read a blog to ease the frustration. Then write some more code.
  14. Lurk on IRC: Connect your favorite IRC reader to irc.freenode.net's #android-dev channel. Leave it up in the background. Only ask questions after you have spent ten minutes trying to figure it out on your own.
  15. Use two monitors: Working on your laptop in the coffee shop will slow you down. You need to spread out windows. At very least, you will want a full screen Eclipse session, the emulator, and a browser with the tutorial to all be easily visible. Three screens may work even better.
  16. Reformat XML files: The layout editor makes a hash of the XML files. Use the 'source/format' command to put them in a reasonable form. You will want to check the "Eclipse/Windows/Preferences/XML/XML Files/Editor/Formatting/Split XML attributes each on a new line" check box. Then use shift-ctrl-F to format it.
  17. Edit XML files with the text editor: After the first couple of layout screens, stop using the slow moving 'properties' gui to change properties. Drop the items using the gui. Use the up/down arrows on the far right outline to get the hierarchy of views and layouts correct, then edit the XML file directly and use the ctrl-space shortcut to bring up possible completions and explanations of the properties.
  18. Plan on Piracy in the MarketPlace: Google has not made the MarketPlace a Happy Place. Apps are copied and reposted with changed names to funnel money around. Lots of scammers are trying to game the system in many ways. Don't plan on making a living solely from AppStore revenues nor plan on Google being responsive.
  19. Use LogCat: It can be difficult in Android to figure out 'what went wrong'. Run the application in the debugger and look at the logcat window. I found it worthwhile to add a new perspective with just a maximized logcat window.
  20. Explore the tools directory: There a lot helpful tools in the sdk's tools directory, such as hierarchyviewer and layoutopt. Each is helpful and there is now shortcut to learning about each tool one at a time.

I could add more if enough people chime in. I hope you find these tips helpful.

Charles Merriam
Thank you for these, particularly #11 because Eclipse's shortcuts are somewhat non-intuitive for me and I need a kick in the pants to learn them.
DrBloodmoney
These are some really original tips. Thank you. Will I sound too greedy if I ask for more ? : )
kunjaan
I'll try to add some extras shortly.
Charles Merriam
+1 for doing all that typing
slf
+1 for originality, I like #6
Silvio Donnini
#2 You can use Scala instead of Java on Android.
Łukasz Lew