12/08/2018, 14:30

5 MUST-HAVE ANDROID LIBRARIES

Libraries are an integral part of mobile application development. They lessen the burden of unnecessary coding for features that are already written by someone somewhere out there, hence minimizing the development time and making way for rapid deployment. A good developer never reinvents the ...

Libraries are an integral part of mobile application development. They lessen the burden of unnecessary coding for features that are already written by someone somewhere out there, hence minimizing the development time and making way for rapid deployment.

A good developer never reinvents the wheel. Then why would you? There’s an ample collection of open source libraries for Android that you can freely use in your apps. Some of them have very specific use that you may seldom utilize while some are so useful at some very basic things that you might want to use them every time you work on a project, like bread and butter.

In the early days, importing a library in an eclipse project was a tiresome process. But, with Android Studio, you can simply add a dependency to your app level build.gradle file to import the libraries over the internet - simply go to the site of any good library and read the instructions. In today’s post, I’m going to tell you about some very handy libraries that you might want to use in almost each of your project.

Ever got tired of instantiating dozens of View instances? Or having a null pointer exception on some instance and wondering how come you missed instantiating one of the 25 or more instances? Here comes Butterknife to the rescue. It’s a view injection tool for binding fields and methods to Android views. Just look at the code snippet below to see how amazing it is:

class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

Just declare the view instances like you as usual do, but before each declaration, annotate it using @BindView() inside of which you just need to write the id of the view you defined in the layout .xml files. After declaration, all you need to do is write one single line of code - ButterKnife.bind(this);

The following code will do exactly the same as written above, but look how Butterknife simplified it. You’ll easily find the difference.

class ExampleActivity extends Activity {
 TextView title;
 TextView subtitle;
 TextView footer;

 @Override public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.simple_activity);

  title = (TextView) findViewById(R.id.title);
  subtitle = (TextView) findViewById(R.id.subtitle);
  footer = (TextView) findViewById(R.id.footer)
   // TODO Use fields...
 }
}

To use it this awesome library, you need to include this in your project by adding it to your app level build.gradle file’s ‘dependencies’ section:

dependencies {
    compile 'com.jakewharton:butterknife:8.4.0'
}

Butterknife also allows you to bind resources, listeners, non-activity views and so on. Have a look here to learn more about this magnificent library.

For beginners or advanced beginners, this is the library to send and receive HTTP requests. This library will save you a lot of time from writing all the tiring long lines of cumbersome codes.

First, add the dependencies in your app’s build.gradle file and syncing the project

dependencies {
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
}

Once synced, you’re good to go with the coding. First you need to instantiate an OkHttpClient and create a Request object.

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

If there are any query parameters that need to be added, the HttpUrl class provided by OkHttp can be leveraged to construct the URL:

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://ajax.googleapis.com/ajax/services/search/images").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("q", "android");
urlBuilder.addQueryParameter("rsz", "8");
String url = urlBuilder.build().toString();

Request request = new Request.Builder().url(url).build();

If there are any authenticated query parameters, headers can be added to the request too:

Request request = new Request.Builder()
    .header("Authorization", "token abcd").url("https://api.github.com/users/codepath").build();

So far the request body is created. Now all we have to do is call asynchronously and get the response like the lines below:

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
    }
}

As you can see, we passed on an anonymous Callback object that implements both onFailure() and onResponse() and inside the onResponse you get the response. Now you can do whatever you like using the Response object. Simple, huh? Visit here to learn more about it.

Both of these libraries are to manipulate ImageView with image loaded directly from some given url. Once you’re done with the dependencies in your build.gradle file, you’re good to go with only these three lines for Glide

Glide.with(context)
    .load("http://pathtoimage.com/graphic.png")
    .into(imageView);

Or Picasso:

Picasso.with(context)
.load("http://pathtoimage.com/graphic.png")
.into(imageView);

Here, imageView is just an ImageView instance on which you’re willing to load the image. Both of these libraries have a lot more features than just loading an image like resizing, cropping, caching etc.

I’ve mentioned both Glide and Picasso because they both have their own pros and cons. One of the main advantages of Glide over Picasso is that it supports GIF. You can also use UIImageLoader or Fresco instead of the aforementioned two as per your requirement.

We have so many ways for communication between different app components, be it communication between activities, between fragments, between activities and fragments or even services.

The pattern EventBus utilizes for the communications is called the publish/subscribe model. In this type of model, there are publishers and subscribers. Publishers are responsible for posting events in response to some type of state change, while subscribers respond to these events. The event acts as an intermediary for exchanging information, isolating and minimizing the dependencies between each side. If you need an 1-to-many communication pattern in your app, then EventBus is there to help you with that. To work with it, first add the following dependency to your build.gradle file:

dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
}

To subscribe your activity or fragment to the event bus, you need to register it first. Likewise, unregister it when the activity or fragment is not running to avoid app crash. Look at the following code snippet to see how it’s done:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

Create a new Event from a standard Java class. You can define any set of members variables. For now, we create a class to accept a result code and a String values.

public class IntentServiceResult {

    int mResult;
    String mResultValue;

    IntentServiceResult(int resultCode, String resultValue) {
        mResult = resultCode;
        mResultValue = resultValue;
    }

    public int getResult() {
        return mResult;
    }

    public String getResultValue() {
        return mResultValue;
    }
}

Inside our Intent service, we can should publish the event. We will simply pass an OK result with a message that will be displayed when the event is received on the Activity.

@Override
protected void onHandleIntent(Intent intent) {

    // do some work
    EventBus.getDefault().post(new IntentServiceResult(Activity.RESULT_OK, "done!!"));
}

We simply need to annotate a method that has this specific event type with the @Subscribedecorator. The method must also take in the parameter of the event for which it is listening. In this case, it's IntentServiceResult.

public class MainActivity extends AppCompatActivity {

@Subscribe(threadMode = ThreadMode.MAIN)
public void doThis(IntentServiceResult intentServiceResult) {
       Toast.makeText(this, intentServiceResult.getResultValue(), Toast.LENGTH_SHORT).show();
}

Go here to learn more about this library.

The Material Design guidelines focus heavily on animation, and if you use it correctly, you can really make your app look polished and make your interactions more intuitive and enjoyable. Animations can be hard, but good libraries make them easy!

For a set of regular View animations, you can use AndroidViewAnimations. Let the author’s animated GIF speak for itself:

alt

Including it is simple, though it does require two other projects as well:

dependencies {
  compile 'com.nineoldandroids:library:2.4.0'
  compile 'com.daimajia.easing:library:1.0.0@aar'
  compile 'com.daimajia.androidanimations:library:1.0.8@aar'
}

And the rest couldn’t be any simpler. Look at the syntax below:

YoYo.with(Techniques.Bounce)
    .duration(700)
    .playOn(findViewById(R.id.usernameField));

This is all for today. Play with these libraries as you wish and try to discover new ones and experiment with them. Chances are, some day your app will end up being built up on libraries rather than your own codes. Until next time, happy coding.             </div>
            
            <div class=

0