Top 5 Android libraries every Android developer should know about
In the last year or so, Android development has really come of age. Android Studio with Gradle at its core is a dash of light after Eclipse. Besides that, there are quite a few open source libraries that we use on a daily basis.
Here is a selection of five of our favorite ones and a list of links where you can find others.
1. 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:
2. 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.
3. EVENTBUS
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();
}
}
}
4. 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 like GreenDAO and ORMLite
5. UNIVERSAL IMAGE LOADER
UIL is a library which provides asynchronous, out of the box loading and caching of images. It’s pretty straightforward to use:
imageLoader.displayImage(imageUri, imageView);
Although Picasso has a nicer API, it lacks in customization. With the UIL configuration builder almost everything can be configured (important for fetching and caching of really large images, which Picasso fails to do).
Good open source libraries will make your development a hell of a lot easier and faster. Popular libraries are often well tested and simple to use. In most cases you can easily import them into your Android Studio project from Maven. Add them into dependencies in your build.gradle file like this:
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.okhttp:okhttp:1.3.0'
compile 'com.squareup.retrofit:retrofit:1.3.0'
compile 'de.greenrobot:eventbus:2.2.+'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.1'
}
and after syncing you will be good to go to implement them into your app.
No comments:
Post a Comment