By Subham Aggarwal | 7/4/2017 | General |Beginners

Underused Android Libraries

Underused Android Libraries

Any experienced developer will tell you that their best code isn’t code they wrote. It’s code they took from someone else’s work.

 

Yes, we developers are innovative problem-solvers, but many of the problems we encounter have already been solved—and the remedies packaged into libraries available to anyone. Why reinvent the wheel when free wheels are everywhere?

Selecting the Right Android Library

When choosing a library, I look for four key features:

  • It provides a consistent and high-quality solution for a real and non-trivial problem.
  • It uses as simple an API as possible.
  • It does not force any changes in my overall architecture.
  • It has a large user base and, preferably, an active developer community.

ButterKnife: The Ultimate Dependency Injection Tool

This is the ultimate dependency injection library for Android.

Gone is the need to directly bind each of your views via a call to findViewById(). Instead, there’s an annotated view that gives you direct access to code. ButterKnife also eliminates the need for boilerplate UI events such as onClick, onTouch, and so on, and replaces them with auto-injected code.

 

View field binding:

class MyButterKnifeActivity extends Activity {
 @BindView(R.id.name) TextView name;
@BindView(R.id.address) TextView address;


 @Override public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.simple_activity);
   ButterKnife.bind(this);   // MUST BE CALLED BEFORE ACCESSING UI FIELDS
   name.setText("etc etc");
 }
}

 

Resource binding:

class ExampleActivity extends Activity {
 @BindString(R.string.username) String username;
 @BindDrawable(R.drawable.graphic) Drawable graphic;
 @BindColor(R.color.bg_color) int bgColor;
 @BindDimen(R.dimen.lower_padding) Float lowerPadding;

 // and no need for getResources().getString()/getDrawable/getColor()
}

 

UI event binding:

@OnClick(R.id.my_button)
public void clickHandler(View view) {
 // onClick logic goes here
}

EventBus

EventBus library turns a problem that’s haunted Android developers for years into a walk in the park. Cross-component communication has never been simpler—use a simple pub/sub model to communicate between any two parts of your system.

 

EventBus usage is straightforward.

  • Create event classes. Working with POJOs here is best:
class NewUserEvent {
 String fullname;
 String address;
 String role;             
 // add getters and setters 
}
  • Create event handling methods in the class—any class that you wish to subscribe for these events:
class MySubscriber {


 @Subscribe
 public void newUserHandler(NewUserEvent event) {
   // handle NewUserEvent
 }

 @Subscribe
 public void newUserHandler(AnotherEvent event) {
   // handle AnotherEvent
 }
}

 

But hey, any half-experienced Android developer would stop and ask at this point: What's the threading model of these handlers? And can I force a handler to run off the main thread if, say, it involves UI component access? Good question…

 

By default, all handler methods run on a worker thread taken from a thread pool that’s allocated and maintained by EventBus itself. If you need a handler method to run on the main thread, expand your subscription annotations as follows:

@Subscribe(threadMode = ThreadMode.MAIN)
public void runOnMainThreadHandler(AnotherEvent event) { … }

 

Warning: Do not overuse this feature! Long-running operations should never be executed on the main thread, and even with quick operations, be careful. Overwhelming the main thread is the surest way to make your app slow, jumpy, and basically less fun to your users.

  • Manage the EventBus registration lifecycle of your subscriber class—that is, when does it connect and when does it disconnect from the bus? A reasonable registration flow for an activity would be:

 

class MySubscriberActivity extends Activity { 

@Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this); // START RECEIVING EVENTS HERE
   }

  @Override
   public void onStop() {
       EventBus.getDefault().unregister(this); // NO MORE EVENTS
       super.onStop();
   }
}


The above is, of course, just an example. You can perform the (un)registration anywhere you choose.

  • And finally, actually fire an event:
EventBus.getDefault().post(new MyEvent("I'm here"));

 

There’s a lot more to know about using EventBus: multicasting events (the default behavior), using sticky events, delivery threads, priorities, and more. But the above is enough for you to get started with this simple, yet powerful, technology.

Picasso: There's a Good Reason Google Uses It Too!

Picasso is the simplest and most robust way of managing image downloading, caching, resizing, and cropping.

 

This code snippet:

Picasso.with(context).load(url).resize(50,50).centerCrop().into(imageView)

 

The code above will achieve many things:

  • Connect to a remote URL
  • Download an image
  • Store it in a local LRU cache which it will also manage for you
  • Resize the original image before loading it into memory
  • Run all of the above on a thread pool managed by Picasso
  • Use the resized image to populate your imageView
  • Before any future runs, check the local cache to ensure a network round trip is really necessary

 

Building the above set of tasks would require many hours of work, even for a master developer. And that assumes you remembered everything.

 

What if you forgot, say, the resize part?

 

Well, on the average Android device, an app gets no more than 50 to 60 Megabytes of RAM, and the pixels-to-bytes factor for most Android devices is 4. This means attempting to load a 13-megapixel image from the SD card would require 52 Megabytes of RAM. In other words, the app would immediately crash.

 

This is just one example of the strength of Picasso. One of the first things I do when optimizing/debugging a media-intensive legacy project is switch all image loading to Picasso. You’d be surprised the impact this one simple step has on app quality.

LeakCanary: Detect Memory Leaks in a Line of Code

Let’s start with the motivation behind this library: memory leaks. Android apps are prone to them, especially if you’re not careful with your coding. In fact, creating memory leaks is very simple. All you need to do is to store an activity reference outside of its context. In fact, even storing a reference to a single view object outside of its activity’s context will create a leak.

 

Why? Because a view—all views, in fact—internally store a context reference to its containing activity. As long as a reference to the view is kept, its containing activity—along with what’s inside it, including drawables, view hierarchy, and resources—cannot be reclaimed by the garbage collector.

 

Keeping a reference to a leaking activity is not always obvious as a static parameter. Whenever you create an inner class or spawn a thread inside an activity, a reference to that activity will be created and the activity may not be reclaimed until that inner class or thread is completed.

 

To use it simply initialize leakCanary with your app’s object onCreate():

public class MyApp extends Application {
 @Override public void onCreate() {
   super.onCreate();
   LeakCanary.install(this);
   // more initialisations
 }
}

 And you’re done. LeakCanary will monitor for memory leaks, and send a notification if it detects one.

 

LeakCanary achieves this magic by auto-injecting an object called ActivityRefWatcher into all of your activities and monitoring their ref count after onDestroy() has been called. A ref count that is > 0 on a destroyed activity can only mean a leak.

Summary

Experienced developers cut days and weeks off their coding and debugging phases using these libraries, so there is no reason you can’t do the same.

 

To sum up, here’s what my selection of Android libraries can do for you:

  • ButterKnife – Auto-injected code will help you do away with much of your app’s boilerplate code. It’s the ultimate code injection for Android. Need I say more?
  • AndroidAnnotations – Use blazing fast auto-generated classes and name-based code injection to save time with no performance penalty over hand-coded logic.
  • EventBus – Decouple components for more robust code, cross-component communication has never been simpler.
  • OkHttp – A clever replacement for HttpURLConnection, with support for asynchronous networking, request redirect route query, local cache query, and more.
  • Picasso – Streamlined image manipulation that’s so good it’s now used by Google. It’s a major time-saver in media heavy projects and certain legacy projects.
  • ActiveAndroid – ORM made easy with no performance overhead.
  • LibStreaming – Real-time video streaming, used by major streaming apps.

 

Are these the only Android libraries worth your time? Certainly not. But I promise you this: using any of them on your next project will make you a much better developer.

 

If you are already using some or all of them, or if you are using alternative libraries, I urge you to share your experiences in the comments below.

By Subham Aggarwal | 7/4/2017 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now