Introducing ART – Android Run Time – a Dalvik Replacement

This article explains the differences between ART vs Dalvik. Once it is mature, it will be a timely switch from CPU-intensive JIT to “potentially” quicker ART, apart from the one-time install lag.


Dx trouble writing output: Too many fields: Conversion to Dalvik format failed with error 2

Android compiles source code into dex files which is executed by Dalvik. While integrating a new library project into the maincode base, I got the above build time error.

While researching the problem, here are some things I came across:

1. Each Android dex file can contain a max of 65, 536 method references (i.e.) a method reference count is incremented by 1, whenever there is a unique reference to a method from an Android project.

2. If a project grows big enough to contain more than ~65K method references, the library files can be built as separate dexes.

3. Dex files can be dynamically loaded in the main activity’s onCreate method. See example.  

4. Even if 2 Android library projects referenced the same Android project, the method reference count is counted twice – provided the 2 Android library projects have different manifest package names (i.e.) package name defined in the manifest node in AndroidManifest.xml file.  

To provide an example of #4 above, see portions of the dex build error stack trace below that caught my attention. It indicates the method reference count for these library projects – all hovering close to the number 6852. The only common library/jar reference in all these library projects referenced the android framework library itself.

Error:Android Dex: [MainProject] 6852

Error:Android Dex: [MainProject] 6964 com.handmark.pulltorefresh.library

Error:Android Dex: [MainProject] 6852


and so on…..

Given the above, some potential work-arounds emerged:

1. Do away with the need for library projects. Package everything into one monolithic structure.

2. Split the project files into multiple dex files.

#1 goes against fundamental software principles of software development – code needs to be developed as re-usable libraries.

#2 is a good long-term solution but is more complex.

The solution: A reasonable medium term solution emerged after understanding #4 more closely. The significance of Package name within the manifest tag in the AndroidManifest.xml file is that it is used as a fully qualifying name to identify Android resources. It does not have anything to do with the package name for the java classes themselves. So I tweaked 1 manifest package name (new library project) to be the same as the top level project (MainProject) manifest package name. And the dex build error was gone!

The following command returns the count of methods in a dex file:


    dexdump -f product.apk | grep method_ids_size

No Resources found that matches the given name

The error in the title is a very common error encountered in Android. There are several common reasons why this could happen. For example,

1. The resource is really missing from (say) a string resource file.

2. The SDK target is set to a version below the required version etc.

However, there is another common reason why this error occurs in IntelliJ – because the dependent or library project is *not* marked as a library project, in addition to including it in the list of module dependencies. This happens frequently while importing existing Android projects into IntelliJ. To resolve this issue, first check if the dependent project is a library project as follows:

1. Open Module Settings in IntelliJ

2. Select the ‘Android Icon’ below the library module.

3. Mark the “Library module” check box selected. Select Save.

Without step #3, Intellij will NOT see resources from a library project, even if the library project has been marked as a dependent module in the main project.

Parcelable vs Serializable

This article has a good explanation of Parcelable vs Serializable. In summary, the downside of serializable is that the run time needs to invoke reflection while serializing each class member, which may be a performance drain for bigger objects that are serialized more frequently. Parcelable solves this problem by explicitly defining how each class member should be serialized. As part of implementing Parcelable, the writeToParcel method should be over-ridden. Some code:

public class DataObject implements Parcelable {
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(strMember1); // Parcelable for strings
        dest.writeInt(member2); // Parcelable for integers                                                                                                                                  

        dest.writeBooleanArray(new boolean[] {boolMember1, boolMember1} ); // Parcelable for booleans

        // Caution: missing data members don’t get serialized

   public void readFromParcel(Parcel source) {
        strMember1 = source.readString();
        member2 = source.readInt();
        // readFromParcel for boolean members
        boolean[] flags = source.createBooleanArray();
        boolMember1 = flags[0];

However, the catch in implementing Parcelable is for large objects, that each time a new class member is added, its the responsibility of the developer to also the add corresponding code in the writeToParcel method. If this is not done, this new class member will not be serialized and the default value when de-serializing the object will be null.

Hence, while deciding whether to implement Parcelable, the trade off is between a minor improvement in performance (vs.) the possibility of introducing errors due to missed writeToParcel implementation for new class members and additional unit testing involved in testing the parceling methods.

Onclick event of the GridView item never gets called…

It is very common to have a click-able UI component (e.g. button) on a GridView item, which in turn sits inside a Android GridView. For example, a GridView may contain a list of thumbnail pictures. Each such picture may have a button or a check mark image (for selecting the image). In such cases, the main event of interest is the OnClick of this button and the Image holder itself. Also depending on the way the code is structured, it may be useful to handle the click event both within this UI component as well as the underlying GridView item.

One common issue is that the over-laying button’s OnClick event swallows the GridView item’s OnClick event – due to this, the GridView item’s OnClick event never gets called. The work-around for this is to replace the Android Button with a TextView styled like a button. This replacement is possible because a Button extends a TextView. The TextView’s OnClick method does not swallow the click event and the OnClick propagates to the GridView item as well, so it can do its own OnClick handling. Some code follows:

public class GridViewAdapter extends ListAdapter {

public View getView(final int i, View gridviewItem, ViewGroup viewGroup) {
// Inflate the gridview item
gridviewItem = inflater.inflate(R.layout.gridviewItem, viewGroup, false);

// Get the TextView that is contained in the gridview item
final TextView textView = (TextView) gridviewItem.findViewById(; // instead of R.Id.button1
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// handle onClick of textView here


Integration with Otto

Otto is a well known library from Square. I recently integrated with Otto into my Android project – the integration was painless. The following blog post illustrates how the code changed for activity-fragment communication, before and after integration with Otto. Also dont miss reading the “Things to Watch out for” section at the bottom of this post.

Before Otto Integration:

MainActivity interacts with and controls (say) 3 fragments.

MainActivity needs to ‘listen’ to (Say) 4 events from these 3 fragments, mainly for coordination amongst fragments. Each fragment then defines an interface that the MainActivity implements. Sample code for Fragment A shows here.

FragmentA code – before Otto:

public class FragmentA extends BaseFragment {

        /* First, define a private member to register callbacks. */

        private IActionACallBack actionACallback = null;

        /* Define an interface that the Activity can implement */

        public interface IActionACallBack() {

            public void actOnActionA();


        /* register the activity with this fragment */

        public void setActionAListener(IActionACallBack callback)  {

            actionACallback = callback;  


        /* When the activity needs to be notified, typically when the fragment is done with its part, call-back the activity that was previously registered with this fragment */

        private void onSomeEventOrWhenFragmentIsDone() {



} // end FragmentA

MainActivity code – before Otto:

public class MainActivity extends BaseActivity implements FragmentA.IActionACallBack, FragmentB.IActionBCallBack, FragmentC.IActionCCallBack {

            // activity code.


            public void actOnActionA() {

                    // switch fragments here – maybe display Fragment B    



} // end MainActivity

Obviously, apart from code bloat in the form of multiple interfaces and callback implementations, the other downside to the above design is the multiple interfaces that the activity needs to implement, which leads to tight-coupling between the activity and the fragment(s). Integration with Otto eliminates this tight-coupling by making activity-fragment communication event based through the Otto bus. Fragments can post events which Activities can subscribe to via the bus. Activities then don’t have to implement multiple interfaces defined within fragments.

After Otto Integration: The following lines of code shows the design after integration with Otto.

FragmentA code – after Otto:

public class FragmentA extends BaseFragment {

        // inject a busprovider object via guice

        @Inject private BusProvider busProvider; // busprovider implementation follows

        // communicate with the activity by posting an interesting event to the bus. This event object (FragmentAInterestingEvent) can take a optional parameter (obj), depending on the business case.

        private void notifyListeners() {

            busProvider.get().post(new FragmentAInterestingEvent(obj));



MainActivity code – after Otto:

public class MainActivity extends BaseActivity { // note: NO interface implementations here!

        // Define all the events that the activity is interested in, within the eventhandler object below. If your app has base and derived classes that need to listen to the same subscribed events, avoid writing subscribe methods in both base and derived classes (original eventhandler implementation here)

        private final Object eventhandler = new Object() {
                public void FragmentAInterestingEvent(final FragmentAInterestingEvent event) {

                public void FragmentBInterestingEvent(final FragmentBInterestingEvent event) {
                }        }  // end eventhandler

        // register eventhandler in onResume
        public void onResume() {

        // un-register eventhandler in onPause
        public void onPause() {

} // end MainActivity

// BusProvider Implementation
public class BusProvider implements Provider<Bus> {
        Bus eventbus = null;    

        public Bus get() {
            if (eventbus == null) {
                eventbus = new Bus(ThreadEnforcer.ANY); // receive callback on any thread, not just the main thread
            return eventbus;

Things to Watch out for:

1. One common issue faced while using Otto for the first time is that the @Subscribe method does not get called. The most common reason for this is that the busprovider object is not the same across different activities. Make sure the the busprovider is a singleton instance across your app. One way is to specify the binding using Guice:


2. Classes that only post events don’t need to register and un-register with the bus.

3. If you use the @Producer annotation (not covered in the above post), make sure to do the initial state handling. Producers provide an ‘immediate’ callback to their subscribers (not just when you expect them to, as on a user event that you have coded up) and its easy to miss the initial state handling.


Notes from OnAndroid 2013 Oct conf: Dalvik VM

This talk was all about Dalvik under the hood. The full slides are available in this SpeakerDeck page. The most useful slides in this talk are towards the end – they contain interesting optimization tips while developing code for Android.

  • Dalvik is optimized for a wide variety of device configurations – 32 MB to 32 GB RAM.
  • Unlike JVM, all classes in Dalvik are compiled into .dex files and packaged into an apk along with res and manifest files. The dex file itself is not compressed though.
  • Java’s JVM is stack-based whereas Dalvik is register-based. The main upside of being a register-based system is lesser instructions and lesser dispatches to accomplish the same task – no push-pop involved and memory footprint is lesser. See slides for an example of instruction optimization. The downside is that complexity of each instruction increases. Java’s JVM is very efficient for desktop machines.
  • Dalvik unifies the constants pool (i.e.) lots of symbols (~estimated at ~60%) are duplicated across classes – only 1 copy is stored across these instances.
  • Dalviks JIT is trace based as opposed to JVM’s method based. Once it figures out a hotspot, it converts it to native and runs the native version from then on.
  • Zygote is the father of all VM’s. When an app is started, the Zygote is forked, to minimize initial load time. The app’s VM  contains a reference to Zygote (with its core libraries) plus the app’s heap + dex files.
  • Development tip #1: Prefer signalling (Notifications) vs Polling.
  • Dev tip #2: Minimize work when there is no user, network or sensor input.
  • Dev tip #3: Monitor the state of the battery. The Android dev site has good tips.
  • Dev tip #4: While looping through Array lists, pre-compute the list size (vs.) using Java’s standard Iterator mechanism. This avoids calling ‘next’ ob every loop.
  • Dev tip #5: Keep garbage collectons low. Avoid short-lived allocations, excessive boxing-autoboxing, pass lists as an argument to a method (instead of returning a list).
  • Dev tip #6: Recycle views and bitmaps.
  • More optimization tips are found here.