Category Archives: Uncategorized

Failed to find provider info for com.example.provider.UniqueContentProvider

The above error arises when the content provider has been declared incorrectly in the manifest.
1. Make sure that this is defined WITHIN the tags

In the above, android:authorities is just the name of a string that should be unique. Its different from the android:name, which is the fully qualified name of your ContentProvider implementation that implements android.content.ContentProvider

2. Although the actual content provider implementation may reside in a library project, the definition should be reside in the androidmanifest.xml of the main project.

Advertisements

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 {
    @Override
    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 {

@Override
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(R.id.textView1); // instead of R.Id.button1
textView.setOnClickListener(new View.OnClickListener() {
@Override
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() {

            actionACallback.actOnActionA();

        }

} // end FragmentA

MainActivity code – before Otto:

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

            // activity code.

            @Override

            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() {
                @Subscribe
                public void FragmentAInterestingEvent(final FragmentAInterestingEvent event) {
                    doSomething();
                    return;
                }

                @Subscribe
                public void FragmentBInterestingEvent(final FragmentBInterestingEvent event) {
                    doSomethingElse();
                    return;
                }        }  // end eventhandler

        // register eventhandler in onResume
        public void onResume() {
                    super.OnResume();
                    busProvider.get().register(eventhandler);
        }

        // un-register eventhandler in onPause
        public void onPause() {
                    super.onPause();
                    busProvider.get().unregister(eventhandler);
        }    

} // end MainActivity

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

        @Override
        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:

        bind(BusProvider.class).in(Scopes.SINGLETON);

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.