Common Android Libraries You Should Use in Every Android Projects.

Balram Pandey
The Android Guy
Published in
7 min readJul 12, 2016

1.ButterKnife

On to my favorite libraries! Let’s start with a test: which of these do you like better?

protected TextView mWelcomeLabel;
protected EditText mUsernameField;
protected EditText mPasswordField;
protected Button mSubmitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWelcomeLabel = (TextView) findViewById(R.id.welcomeLabel);
mUsernameField = (EditText) findViewById(R.id.usernameField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mSubmitButton = (Button) findViewById(R.id.submitButton);
}

or

@InjectView(R.id.welcomeLabel) protected TextView mWelcomeLabel;
@InjectView(R.id.usernameField) protected EditText mUsernameField;
@InjectView(R.id.passwordField) protected EditText mPasswordField;
@InjectView(R.id.submitButton) protected Button mSubmitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ButterKnife.inject(this);
}

The latter code is more concise and understandable, don’t you think? The second block of code is using a library called ButterKnife, which uses annotations to “inject” views by creating boilerplate code for you. ButterKnife is small, simple, and lightweight, and because it makes your life as a developer easier, you should pretty much always use it. It would be great if the Android SDK itself could improve in this manner!

There are additional attributes you can use to make OnClickListeners and other common, verbose aspects of Android development easier to write and understand.

Below is all you need to include this library automatically in your Android Studio projects. Just add this one line to your app’s build.gradle file (in app/src):

compile 'com.jakewharton:butterknife:5.1.2'

You need to add it in the dependencies section, like this:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.jakewharton:butterknife:5.1.2'
}

2.Picasso

You may not need this for every app, but if you are downloading images from the web, then you should use Picasso. There are a few popular libraries that do this kind of work, but Picasso is my favorite because it’s simple and easy and I really like how the API is written. Code should always be this intuitive and pleasurable to use!

If you have never downloaded an image from the web in Android, then perhaps you don’t know why this is so helpful. Here are the steps you need to take to download an image with only the standard Android APIs:

  1. Get Image URL
  2. Create AsyncTask to download image
  3. Execute AsyncTask
  4. Store result in Bitmap
  5. Set bitmap as source
  6. Cache image for future

That’s a lot of work! Doesn’t it seem like you should just be able to provide the URL to an ImageView and magically have it appear? Check out the steps if you use Picasso:

  1. Get image URL
  2. Load it into an ImageView with one line:
Picasso.with(this).load(imageUrl).into(mImageView);

This last line says, “With this context, load this image URL into this ImageView.” Not only is it short and sweet, but it also takes care of those other steps mentioned above behind the scenes. It’s an asynchronous download and the image is automatically cached for future use. It also has additional features that make it helpful for debugging and other work.

Once again, adding it to your project is super easy in Android Studio. Just add this line to your dependencies section (like ButterKnife above):

compile 'com.squareup.picasso:picasso:2.3.3'

If you want to see this in action, I cover using it in Build a Self-Destructing Message App and Implementing Designs for Android.

Downloading things other than images from the web? Check out android-async-http!

3.GSON

Gson is a Java library used for serializing and deserializing Java objects from and into JSON. A task you will frequently need to do if you communicate with APIs. We mostly use JSON because it’s lightweight and much simpler than XML.

// Serialize 
String userJSON = new Gson().toJson(user);
// Deserialize
User user = new Gson().fromJson(userJSON, User.class);

It also plays nice with the next library:

4.Retrofit

From their site: “Retrofit turns your REST API into a Java interface.” It’s an elegant solution for organizing API calls in a project. The request method and relative URL are added with an annotation, which makes code clean and simple.

With annotations, you can easily add a request body, manipulate the URL or headers and add query parameters.

Adding a return type to a method will make it synchronous, while adding a Callback will allow it to finish asynchronously with success or failure.

public interface RetrofitInterface {    // asynchronously with a callback
@GET("/api/user")
User getUser(@Query("user_id") int userId, Callback<User> callback);
// synchronously
@POST("/api/user/register")
User registerUser(@Body User user);
}
// example
RetrofitInterface retrofitInterface = new RestAdapter.Builder()
.setEndpoint(API.API_URL).build().create(RetrofitInterface.class);
// fetch user with id 2048
retrofitInterface.getUser(2048, new Callback<User>() {
@Override
public void success(User user, Response response) {
} @Override
public void failure(RetrofitError retrofitError) {
}
});

Retrofit uses Gson by default, so there is no need for custom parsing. Other converters are supported as well.

5.Event Bus

EventBus is a library that simplifies communication between different parts of your application. For example, sending something from an Activity to a running Service, or easy interaction between fragments. Here is an example we use if the Internet connection is lost, showing how to notify an activity:

public class NetworkStateReceiver extends BroadcastReceiver {    // post event if there is no Internet connection
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
// there is Internet connection
} else if(intent
.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
// no Internet connection, send network state changed
EventBus.getDefault().post(new NetworkStateChanged(false));
}
}
// event
public class NetworkStateChanged {
private mIsInternetConnected; public NetworkStateChanged(boolean isInternetConnected) {
this.mIsInternetConnected = isInternetConnected;
}
public boolean isInternetConnected() {
return this.mIsInternetConnected;
}
}
public class HomeActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this); // register EventBus
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this); // unregister EventBus
}
// method that will be called when someone posts an event NetworkStateChanged
public void onEventMainThread(NetworkStateChanged event) {
if (!event.isInternetConnected()) {
Toast.makeText(this, "No Internet connection!", Toast.LENGTH_SHORT).show();
}
}
}

6. ActiveAndroid

ActiveAndroid is an ORM for Android. It’s an abstraction over SQLite which allows you to communicate with a database on a device without writing SQL statements. An Object that extends ActiveAndroid Model can be saved to the database like this:

user.save();

which can easily replace a big SQL statement like this:

INSERT INTO Users (Nickname, Name, Address, City, PostalCode, Country) VALUES ('Batman','Bruce W','Palisades 21','Gotham','40000','USA');

An example of retrieving all users:

List<User> users = new Select().from(User.class).execute();

of which SQL counterpart would look like this:

SELECT Nickname, Name, Address, City, PostalCode, Country FROM Users;

ActiveAndroid is a nice way to remove a lot of boilerplate code used for working with databases. There are other open source solutions likeGreenDAO and ORMLite.

7.LeakCanary

Did you know that coal miners used to take a canary in a cage down the mines so that if the gas got so bad that the canary died, it would be their signal to leave the mine. Well, LeakCanary is similar, but instead of testing for gas leaks, it’s a memory leak detection library for Android and Java. It helps to detect easily leaking objects by just adding a couple of lines of Java code to your existing code. It’s free and very easy to use. Similar to Dagger, the development of LeakCanary is also led by Square.

Again, LeakCanary is licensed under Apache License 2.0 and can be found fromhttps://github.com/square/leakcanary.

8.Libphonenumber

When it comes to parsing and formatting phone numbers, there aren’t many good and free solutions available to the developer. Thankfully, the Google team has come up with a library called Libphonenumber. It is probably the best and most comprehensive library for parsing, validating and formatting phone numbers. Other than the name, which doesn’t roll off the tongue, it’s great!

It has a quite simple and easy to use API and has also been ported to other languages off the JVM such as C# and PHP. The development of Libphonenumber is led by Google, and it is licensed under the Apache License 2.0. For downloads, navigate here:https://github.com/googlei18n/libphonenumber

How to Discover Libraries

If you are new to the open source community, you may be wondering how you can find libraries like this on your own. It’s really just a mindset. Every time you go to add new code, ask, “Has somebody done this already?”

  • Ask Google
  • Ask GitHub
  • Ask StackOverflow
  • Ask a friend

Then, once you find a library that looks interesting, remember the most important two letters for researching open source libraries: vs.

Whenever I’m researching a library, I google the library’s name followed by “vs”. Then in autocomplete I see competing libraries that the one I’m researching has been compared to. That helps me evaluate similar libraries and choose the best one for me. Check out this example of ButterKnife:

RoboGuice, AndroidAnnotations, and Dagger are all libraries that do similar injection things like we saw ButterKnife does for us.

Lastly, you can utilize social media and newsletters to keep an eye on the open source landscape. I passively monitor the following and bookmark any libraries that look useful.

Remember, one of the main goals of programming is to be efficient and complete. Learning how to use the work of others to augment your own is a valuable skill even the most seasoned professionals rely on.

Refrence:

https://github.com/bumptech/glide — Glide Image loading framework for Android

http://www.vogella.com/tutorials/AndroidButterknife/article.html — Android Butterknife, view injection framework

https://github.com/square/otto — Otto — Event Bus for Android

http://square.github.io/retrofit/ — Retrofit — A type-safe REST client for Android and Java

http://code.google.com/p/achartengine/ — AChartEngine, Charting Engine

http://ormlite.com/ — ormLight ORM mapper

http://greendao-orm.com/ — GreenDAO from Markus Junginger, ORM Mapper

https://github.com/google/Dagger — Dagger2 — dependency injection framework for Java and Android

http://code.google.com/p/android-scripting/ — Android Scripting, allows to run scripting languages on Android

--

--