Networking Libraries for Android Developers

            Network calling is one of the most common task which Android Developers has to do on the daily basis. Most of the android applications these days involve some form of network operations be it Facebook, Gmail, Youtube, Spotify or any other popular application.

Here I am introducing some of the most common android networking libraries available for android developers along with their advantages and disadvantages. 

AsyncTask :
      AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Advantages of using AsyncTask :

  • It is very simple to use, there are set of methods which you have to call and perform your operations accordingly.
  • It does not involve any complex thread handling hence good to work with specially for new developers.

Disadvantages of using AsyncTask :

  • When an app is rotated, the entire Activity is destroyed and recreated. When the Activity is restarted, your AsyncTask reference to the Activity is invalid, so onPostExecute() will have no effect on the new Activity. This is one of the major issue which you have to face during orientation changes.
  • Cancellation of Asynctasks does not work the way developer’s assume. Meaning that even on calling AsyncTask.cancel(), it doesn’t get cancel it just put it in the halt so you have to check via logs if it actually get cancelled or not.
  • Concurrent network connection is very difficult to handle using AsyncTask.

AsyncTask is an older way of network calling which might looks easy for a newbie developer but it can create a lots of issues in the long run, so it is not a recommended way to make your network calls in a serious large project.

Volley :
        Volley is an HTTP library that makes networking for Android apps easier faster. It is been officially provided by Google as part of AOSP as well as they use it in their inhouse applications such as Gmail, Google News, etc..

Advantages of using Volley :

  • No need to write code for network call, it is managed by  volley itself. Whole life cycle is maintained by volley as well.
  • Multiple concurrent network connections can be simultaneously handled by Volley which was not the case with AsyncTask.
  • Caching support provided by Volley is pretty good.
  • Its very easy to cancel requests and then resend requests using it.
  • No need of additional library for image caching unlike Retrofit in which Picasso or other similar image caching library is required to use.
  • For large compressed images Volley works very good compared to other available networking libraries.

Disadvantages of using Volley :

  • Multipart requests are one of the major issues in volley. 
  • Image loading capabilities in Volley are not that great and are very limited to compared to a dedicated image caching library like Picasso or Glide.
  • Documentation is very less compared to Retrofit so bit difficult to use. However there are some good unofficial resources for volley has been created by several developers supporting it over there blogs and GitHub.

Retrofit :
      Retrofit is an open source networking library developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp. This is one of the most popular networking library among developer community.  Retrofit provides several features which any of the above libraries doesn’t provide.

Advantages of using Retrofit :

  • Compared to Volley, it provides excellent API documentation and have good support in communities! Very easy to add into the projects.
  • It is very simple to use and keeps the code cleaner as well by having interface approach for network calling.
  • Compatible with most of the Serialization libraries with GSON is supported by default. You can also write your own serialization code and can use it with Retrofit.
  • Works excellent with other third party libraries such as  Picasso, DBFlow, RxJava and many more.
  • With version 1.6, OkHttp is now dependent on Okio, which makes it more easier to access and save memory and CPU. 
Disadvantages of using Retrofit :

  • Memory error handling was not good although a significant improvement is already provided with Retrofit 2.0.
  • Unlike Volley there is no inbuilt image caching support so a third party library is must to use if image loading is required.

Conclusion :

There are several other networking libraries used by many developers such as Fast Android Networking, HttpUrlConnection, Apache HttpClient (although google suggest not to use HttpClient anymore ) and many more.

So with this much libraries how to decide which one to use? This question seems simple but it isn’t as every library has its own advantages and disadvantages so as a developer you have to be careful before choosing any of the  libraries depending upon your project usage.

Personally I am a big fan of Retrofit and use it as part of my day to day development as it is simple to use and have lots of features as well as excellent support from both android community and Square.

I hope this article help you to choose best networking library for your android project.


Firebase Cloud Messaging (FCM) Android Example and Tutorial

       In this Firebase Cloud Messaging tutorial, we will see how to send push notification to android device using Firebase Cloud Messaging. So let’s begin.

Why FCM over GCM?
        Previously Google has its messaging service named GCM (Google Cloud Messaging). But then there are some grey area reasons to switch to FCM.

1. Google is investing in Firebase, making it its unified mobile platform. Over the last few years, Google have expanded GCM to send messages to multiple platforms beyond Android: iOS and Chrome. Firebase is known for being cross platform, so FCM now makes a natural fit in the Firebase suite of features designed for Android, iOS, and mobile web.

2. With FCM we have Firebase console available to send push notifications on a click; in addition to FCM sever APIs that can be called from backend server to send push notifications.

3. The registration token lifecycle is very much simplified with FCM.

So now we have good reason to learn FCM, let’s start configuring FCM for your project. This is one-time process.

Step 1 : Create simple Android project in Android studio.
Step 2 : Get your package name from AndroidManifest.xml. Mention user permission for Internet access in AndroidManifest.xml file.


Step 3 : Go to firebase console and create a new project.


Step 4 : Window will appear as below. Give a project a name, select your country and click on “CREATE PROJECT” BUTTON


Step 5 : Now click on Add Firebase to your Android App.



Step 6 : Mention package name that you got from step 2.



Click on “ADD APP” button. google-services.json file will get downloaded; add to your project as shown below.


Click on “CONTINUE” button. Follow step as shown in figure and click FINISH.


Now we are ready with setup. Lets start with Implementing Firebase Cloud Messaging
Create a class “MyAndroidFirebaseMessagingService.java” extending “FirebaseMessagingService”

MyAndroidFirebaseMessagingService.java

package fcm.android.com.firebasecmdemo;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;


public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // creating notification

        Intent i= new Intent(this, TargetActivity.class);
        PendingIntent pi= PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder bn= new NotificationCompat.Builder( this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("CTE FCM Tutorial")
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel( true )
                .setContentIntent(pi);
        NotificationManager nm= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(0, bn.build());
    }
}

In above code we have created PendingIntent for opening TargetActivity when user clicks on received notification.

Simplest TargetActivity.java can be as follow:

TargetActivity.java

package fcm.android.com.firebasecmdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class TargetActivity extends AppCompatActivity {

        private TextView textView ;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textView = (TextView)findViewById(R.id.message);
            textView.setText("The Target Message Can Be Shown Here ");
        }
    }


Now we have to define the above service in our AndroidManifest.xml file. So go to manifest and modify as follows.


Complete AndroidManifest.xml is as below:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fcm.android.com.firebasecmdemo">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <activity android:name=".TargetActivity">

        </activity>

    </application>

</manifest>


That’s all. Your app is ready to receive notifications.

Sending Push Notification using Firebase Console

Go to firebase console and select the app you created.
From the left menu select notification.
Click on new message.


Set the message, select your application package from dropdown as shown in below.
Click SEND MESAAGE.



Those who have installed your application will get the push notification.



Download Complete Project here


Cannot resolve symbol SnackBar in Android

        Are you facing an error "Cannot resolve symbol SnackBar" while trying to design your first snackbar ? Lets see how to resolve it..


Now on the left side Expand Gradle Scripts and select build.gradle

Now, Goto File -Project Structure


Now click on the "+" icon at the top and add  library dependency.


Now select com.android.support.design library and click OK. After adding the dependency this should get added to gradle script as shown below



Now go to your jave file and check, you should see something like the below. Press Alt + Enter, you can see the corresponding file will get imported.





Snackbar in Android Material Design Example

      In this tutorial lets discuss the new UI element introduced in material design - Snackbar. Snack bar is an UI element design for user feedback. It shows message at the bottom of the screen which disappears after after a timeout or after user interaction elsewhere on the screen or by swiping right  the Snackbar

Ripple Animation Tutorial with Example in Android

Material Design Animations

1.Touch Feedback- Ripple Animation
2. Activity Transition Animations
-Explode Animation
- Slide Animation
-Fade Animation
-Shared Element Transition Animation
3. Circular Reveal Animation

Getting Started with Android Material Design

       Here we are going to cover topic Material themes, which is most talked feature that got introduced with Lollipop release. We will learn how to setup project to use material theme in pre-Lollipop and Lollipop and above versions Ie. API 21 and above.

Introduction to material design in Android

     Material design is a comprehensive guide for visual, motion, and interaction design across platforms and devices. 
To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21) and above.

Android provides the following elements for you to build material design apps:
A new theme
New widgets for complex views
New APIs for custom shadows and animations
Following are the major introduction with Material Design APIs.

Material Theme
The material theme provides a new style for your app, system widgets that let you set their color palette, and default animations for touch feedback and activity transitions.
Lists and Cards
Android provides two new widgets for displaying cards and lists with material design styles and animations:

View Shadows
In addition to the X and Y properties, views in Android now have a Z property. This new property represents the elevation of a view, which determines:

  • The size of the shadow: views with higher Z values cast bigger shadows.
  • The drawing order: views with higher Z values appear on top of other views.

Animations
The new animation APIs let you create custom animations for touch feedback in UI controls, changes in view state, and activity transitions.

These APIs let you:

  • Respond to touch events in your views with touch feedback animations.
  • Hide and show views with circular reveal animations.
  • Switch between activities with custom activity transition animations.
  • Create more natural animations with curved motion.
  • Animate changes in one or more view properties with view state change animations.
  • Show animations in state list drawables between view state changes.
  • Touch feedback animations are built into several standard views, such as buttons. The new APIs let you customize these animations and add them to your custom views.

We will see these things one by one in coming posts.


AngularJS Events Example

    Event handling in AngularJS is pretty simple. There are ample events in AngularJS for better user interaction. We can handle DOM events like mouse clicks, moves, keyboard events etc.,

ng-focus example in angularjs

      ng-focus directive executes when an element gets focus. This can be used in many different ways and below I have represented few of the examples.


ng-copy, ng-cut, ng-paste example in AngularJS

        ng-copy, ng-cut, ng-paste are some basic AngularJS events used to perform copy (Ctrl + C), paste (Ctrl + V) and cut (Ctrl + X) action that we perform using keyboards. Lets see them with some example.


ng-change example in AngularJS

    ng-change event directive is fired when there is change in the input value or in other words whenever your HTML element changes ng-change is triggered.

ng-change syntax : 

<ng-change
  ng-change="expression">
...
</ng-change>

Lets see this event directive in action with some simple examples.

Example 1: Change in Checkbox element
    So in this example we are incrementing the counter($scope.counter) whenever the checkbox is selected or unselected. The output gif would explain it much better.

<!DOCTYPE html>
<html>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
 <div ng-controller="myCtrl">
  <p>Check :</p>

  <input type="checkbox" ng-model="myValue" ng-change="myFunc()" />

  <p>The Checkbox has changed {{count}} times.</p>
 </div>

 <script>
  angular.module('myApp', []).controller('myCtrl',
    [ '$scope', function($scope) {
     $scope.count = 0;
     $scope.myFunc = function() {
      $scope.count++;
     };
    } ]);
 </script>
 
</body>
</html>


Output : 
Example 2 : Change in Dropdown element
   In this example, we have invoked the counter incrementing function when the drop down element is changed

<!DOCTYPE html>
<head>
<script
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp">
 <div ng-controller="myCtrl">
  <select ng-change="myFunc()" class="form-control"
   ng-model="selectDemo">
   <option>ONE</option>
   <option>TWO</option>
   <option>THREE</option>
  </select> <br /> <br />

  <p>
   Total number of times drop down selected:<b>{{count}} </b>
  </p>
 </div>

 <script>
  var app = angular.module("myApp", []);
  app.controller('myCtrl', [ '$scope', function($scope) {
   $scope.count = 0;
   $scope.myFunc = function() {
    $scope.count = $scope.count + 1;
   }
  } ]);
 </script>
</body>
</html>


Output 

Hope  these examples gives a good understanding on ng-change event directive in AngularJS.


ng-blur example in AngularJS

       AngularJS ng-blur event directive fires when an input element loses its focus. In case if you want to call an function or fire an event ng-blur helps. This angularjs ng-blur event directive is supported by <input>, <select>, <textarea> elements.

AngularJS Include html example and tutorial

         Include in AngularJS is an interesting topic where you can embed external Html file into another html file. This feature is not possible in regular Html file without angular JS. ng-include is the AngularJS directive used to achieve this functionality. 


AngularJS Scope Tutorial

      As we already know, Angular JS consists of Model, View and Controller

View - it is the HTML portion
Controller - Controllers are javascript functions that controls the data of AngularJS applications
Model  - is data of AngularJS applcation

So, Scope is Model in AngularJS

     Scope in AngularJS is like a bridge between controller and view and you need scope every time you create a controller. Scope is nothing but a Javascript object. Scope is available for both View and Controller.  

Lets see this with an example that will give a clean picture of what we are talking theoretically..

AngularJSScope.html

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<p>My Name is <b>{{name}}</b></p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name= "Rob";
});
</script>

</body>
</html>

Lets see this code as Model, View and Controller

Controller
     Controller is nothing but a Javascript function. Every controller should have scope - $scope. The scope is a JavaScript object with properties and methods, which are available for both the view and the controller.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name= "Rob";
});
</script>

View
     View is what displays your data. So the property from controller is displayed here
<div ng-app="myApp" ng-controller="myCtrl">
<p>My Name is <b>{{name}}</b></p>
</div>

Model
$scope.name= "Rob";

scope is the model.

Output of the program

My Name is Rob

Hope this tutorial helps you to understand the below stuff :
  • Scope in AngularJS
  • Relating model scope AngularJS



Filters in AngularJS Tutorial with example

        Filters in AngularJS formats the value of expression for display to the user. There are many number of filters in AngularJS but the following are commonly used

Tables in AngularJS Example

       In this tutorial lets see how to design AngularJS tutorial using ng-repeat directive. Generally tables are repeating structure, so ng-repeat directive can be used to draw tables easily..

Method in AngularJS Example

        In this tutorial lets see how to define and invoke a AngularJS method from html. Methods help us to reuse functionality across your HTML code. So we are going to input two fields from the UI, append both in the method and display it back.