Wednesday, 4 April 2018

Difference between volley and retrofit library

Volley Library:
Volley is a networking library, developed by Google engineers. It was introduced in Google IO 2013, it offers great features like synchronous requests, asynchronous requests, prioritization, making multiple requests at the same time, ordered requests and of course caching. But one of the major problems faced by developers using this library is that it lacks detailed official documentation. Hence if you wish to learn more about it please refer to some of my tutorials:
1.       Android Volley Tutorial
Retrofit Library v1.9.0:
On the other hand Retrofit is a clean, simple, and light library for Android by Square, Inc. In other words, Retrofit is a REST client for Android, through which you can make easy to use interfaces which can turn any Android app into a powerful one. What makes it different is that, Retrofit can perform Async and sync requests with automatic JSON parsing without any effort. This feature alone makes it powerful enough to make a contender for this comparison. Although it has many more easy to use features, please refer to one of my tutorials to read more about them:
1.       Android Retrofit Example

Android Volley vs Retrofit
1) Request Execution
One of the most important factors effecting the code complexity is, how a request is executed in your code. In background or in foreground? As you may know that Android OS does not allow the network interaction on main thread, it throws a NetworkOnMainThreadException. To avoid this you may need to do all the network processing in background. As a matter of fact both Android Volley and Retrofit support the background requests. Also both of them are designed in a way, that you may not have to write huge amounts of code to perform such requests. Although if you wish to do a request in foreground, even that it possible in both. As there are situations when you may want to block user from going further ahead in your app until a response is captured from web API.
2) In-Built Request Types
The data returned from a web service always complicates the implementation, but thankfully now with help of these libraries almost all types of responses can be captured. Android Volley can capture four types of responses automatically through these requests:
1.       StringRequest – Make this type of request and the returned data is parsed and converted in to a String.
2.       JsonObjectRequest – This type of request converts the response in to a JSONObject.
3.       JsonArrayRequest – Make this type of request and response is automatically converted into a JSONArray.
4.       ImageRequest – This type of request converts the response into a decoded bitmap automatically.
On the other hand Retrofit can parse many other types of responses automatically like:
1.       Boolean – Web API response needs to be a String boolean.
2.       Integer – Web API response needs to be an integer.
3.       Date– Web API response should be Long format date.
4.       String – Web API response needs to be in String format.
5.       Object – Web API response needs to be in Json object.
6.       Collections – Web API response needs to be in a String Format.
Now when comparing Android Volley vs Retrofit, volley may have image parsing feature but it cannot convert a Json object directly into a POJO (Plain Old Java Object). On the other hand retrofit can automatically convert a JSON object into a POJO, but lacks image parsing.
3) Retry Mechanism
One of the great things about volley is that it supports retries on request timeout. While creating requests with volley, we can set a retry policy by using setRetryPolicy method. By default a volley request timeout time is set to 5 seconds. But if you wish to change the policy, it supports that too. You can specify these parameters according to your needs:
·         Timeout
·         Number Of Retries
·         Back Off Multiplier
Retrofit on the other hand does not have a retry mechanism as of now. Although I just saw their road map for 2.0 version, they might have a retry mechanism then. Therefore as of now when comparing Android Volley vs Retrofit, Retrofit loses this one.
4) Caching
Android Volley library has a very elaborate caching mechanism. This is one of the best features of volley. When a request is made through volley first it is checked in the cache. If an appropriate response is present in cache then it is parsed and returned directly to main thread, else a network request is made. This whole functionality can be customized, to support your requirements. If you wish to learn more about it please go through this document.
Retrofit on the hand, does not support caching. Although it can implement RFC 2616 caching which is the spec for HTTP caching, through the OkHttpClient. As stated in this document. Therefore when comparing caching between Android Volley and Retrofit, Volley takes this one too.
5) Loading Images
Volley library has a special type of request to get images from network called ImageRequest. When this type of request is made, response is captured as a bitmap. Also it supports the resizing of returned image in the worker thread itself, which saves a lot of coding. Volley also has a NetworkImageView class which can be used with ImageLoader class, to automatically load images, whenever the NetworkImageViewappears. Read this tutorial for more information about it.
As of now Retrofit does not support the loading of images, the way they are loaded in Volley. But it can be combined with OkHttpClient to support the loading of images. Hence volley takes this one too.
6) Code Complexity
Both the libraries Android Volley and Retrofit are very easy to implement. If you compare them with primitive ways of accessing a web API, both of them would come out as a winner as they can phenomenally reduce your code base. But in my opinion when you compare the Android Volley vs Retrofit, the later one- Retrofit wins this one. As there is not much to customize in Retrofit. Its a simple yet powerful library. Volley on the other hand is highly customizable and has a greater code complexity.
Conclusion
After thoroughly comparing the major features between Android Volley and Retrofit. In my personal opinion Volley is a better library. It may be a little complex but it offers much more features than Retrofit. Volley not only supports caching of requests but can also load images automatically. But one of the best things about Retrofit is that it supports automatic parsing of responses, to their respective data types. And its light too. Hope this Android Volley vs Retrofit comparison helped you. Connect with though Facebook, Google+, and Twitter for more updates.

Monday, 3 April 2017

Some important points of Abstract class


Some important points of Abstract class-

- We can't create the object of abstract class but abstract class have constructor.
- Abstract class constructor is called via super() call from child class constructor.
- Abstract class does not allow abstract method static. if you does it's abstract method static then compiler gives you compilation error message - 
     illegal combination of modifiers: 'abstract' and 'static' .
- We can apply static with non-abstract method inside Abstract class.

public class AbstarctionDemo extends  MarketChoice{
public AbstarctionDemo(String[] productName) {
super(productName);
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
// TODO Auto-generated method stub
        String[] productName= {"mouse","keyboard","desktop","cpu","speaker"};
MarketChoice marketChoice= new AbstarctionDemo(productName);
marketChoice.getDetails();
}

@Override
public void getMarketDetails() {
// TODO Auto-generated method stub
//marketChoice
}
}


abstract class MarketChoice {

protected String[] pName;
//Abstract class constructor  
public MarketChoice(String[] name){
pName=name;
}
public abstract void getMarketDetails();
 void getDetails(){
for (String string: pName) {
System.out.println(string);
} 
}

}

Sunday, 2 April 2017

Important features of java 8


Some important features of java 8 are listed below-

  • forEach() method in Iterable interface
  • default and static methods in Interfaces
  • Lambda Expressions
  • Java Time API
  • Java Stream API for Bulk Data Operations on Collections


1. forEach using Map and List interface

EXAMPLE-

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Java8Feature {

public static void main(String[] args) {
// TODO Auto-generated method stub
Java8Feature obj = new Java8Feature();
System.out.println("*** forEach with Map ***");
obj.myMapIterator();
System.out.println("*** forEach with List ***");
obj.myListIterator();
}

void myMapIterator() {
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

//1. Filter map using normal way
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() +" Count : "+ entry.getValue());
}

//2. Filter map using Lambda expression
items.forEach((k, v) -> System.out.println("Item : " +k +" Count : " + v));

//3. Filter map using Lambda expression
items.forEach((k, v) -> {
System.out.println("Item : " + k +" Count : " + v);
if ("E".equals(k)) {
System.out.println("Hello E");
}
});
}

void myListIterator() {
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");

//1. Filter list using normal way
for (String string : items) {
System.out.println("Item : " + string);
}

//2. Filter list using Lambda expression
items.forEach(sanjay -> System.out.println(sanjay));

//3. Filter list using Lambda expression
items.forEach(aaa -> {
if ("C".equals(aaa)) {
System.out.println("Lambda expression");
}
});
//4. Filter using method reference 
items.forEach(System.out::print);   
              // Work like below 
              //items.forEach(i-> System.out.println(i));

//5. Stream and filter
items.stream()
.filter(s->s.contains("B"))
.forEach(System.out::println);
}
}

2. default and static methods in Interfaces


default method of java 8 gives a flexibility to modify or add new upcoming feature in future on existing interface. default method does not effect to all other implementer classes if something is changed on default method, because default method is optional for exiting implementer classes to use default method even not need to override it by all implementer classes.

default method does not create ambiguity if 2 interface having same default method name. its is accessed via interface name.

EXAMPLE-


public class Java8InterfaceDefaultMethod implements IConsumerUpdate ,IMarketProduct ,IMarketInventry{

public static void main(String[] args) {
// TODO Auto-generated method stub
Java8InterfaceDefaultMethod obj = new                                                                    Java8InterfaceDefaultMethod();
int saleCount = obj.getProductSaleCount(10);
System.out.println("Product sale count : " + saleCount);

String pName = obj.getProductName();
System.out.println("Product Name : " + pName);
obj.getConsumer();
String pQuality=IMarketProduct.getProductQuality();
System.out.println("product quality : " +pQuality);
}

@Override
public int getProductSaleCount(int saleCount) {
// TODO Auto-generated method stub
return saleCount;
}

@Override
public int getInventryCount() {
// TODO Auto-generated method stub
return 0;
} 
}

interface IMarketProduct {
String productName = "MacBook pro";
String productQuality = "Normal";
int getProductSaleCount(int count);

default String getProduct() {
return productName;
}
static String getProductQuality() {
return productQuality;
}
}

interface IMarketInventry {
String name = "Windows laptop";

int getInventryCount();

default String getProductName() {
return name;
}
}

interface IConsumerUpdate {

default void getConsumer() {
System.out.println("I am Consumer");
}

}

3. Lambda Expressions


public class ThreadEvenOdd {

    int inputNum=13;

public ThreadEvenOdd(int a) {
super();
this.inputNum = a;
}

public static boolean checkPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int inputNumber=13;
ThreadEvenOdd obj = new ThreadEvenOdd(inputNumber);

/**
* Using Lambda expression introduced in java 8
*/
Runnable runnable = () -> {
// TODO Auto-generated method stub
for (int i = 0; i < obj.inputNum; i++) {
try {
if (i % 2 == 0) {
   System.out.println("Even nuber is: " + i);
}
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

};
/**
* using java 7
*/
Runnable runnable2 = new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < obj.inputNum; i++) {
try {
if (i % 2 != 0) {
System.out.println("odd nuber is: " + i);
}
Thread.sleep(0);
} catch (Exception e) {
e.getMessage();
}
}
}
};

/**
*  Using Lambda expression introduced in java 8
*/
Runnable runnable3 = () -> {
// TODO Auto-generated method stub
for (int i = 2; i < obj.inputNum; i++) {
if (checkPrime(i)) {
System.out.println("Prime number " + i);
}
}

};
Thread t = new Thread(runnable);
Thread t1 = new Thread(runnable2);
Thread t2 = new Thread(runnable3);
t.start();
t1.start();
t2.start();
}


}

Monday, 27 March 2017

Important features of java 7

There are a number of features in Java 7. 
Some of them are listed below-
  • diamond operator
  • strings in switch statements, 
  • multi-catch exception handling, 
 1. Diamond operator
// Old
way-

Map<String, List<Moments>> momentsList = new HashMap<String, List<Moments>>();


//New way-

Map<String, List<Moments>> momentsList = new HashMap<>();

2. Strings in switch statements

// Old way-

private void Show(Profile p) {
String status = p.getStatus();
if (status.equalsIgnoreCase(NEW)) {
newProfile(p);
} else if (status.equalsIgnoreCase(OLD)) {
validateProfile(p);
} else if (status.equalsIgnoreCase(PENDING)) {
pendingProfile(p);
}
}
// New Way-

private void Show(Profile p){
    String status = p.getStatus();
    switch(status) {
        caseNEW:
        newProfile(p);
        break;
        caseOLD:
        validateProfile(p);
        break;
        casePENDING:
        pendingProfile(p);
        break;
        default:
            break;
    }

}

3. Exception handling

// Old-
public void oldMultiCatch() {
try {
methodThrowsThreeExceptions();
} catch (Exception1 e) {
// e.getMessage();
} catch (Exception2 e) {
// e.getMessage();
} catch (Exception3 e) {
// e.getMessage();
}
}
// New-

public void newMultiCatch() {
try {
methodThrowsThreeExceptions();
} catch (Exception1 | Exception2 | Exception3 e) {
// log all Exceptions
// e.getMessage();

}
}

4. multi multi-catch

public void multiMultiCatch() {
  try{ 
   methodThrowsThreeExceptions(); 
  } catch(Exception1 e) { 
   // e.getMessage(); 
  } catch(Exception2 | Exception3 e) { 
   // log all Exceptions
   //e.getMessage(); 
   } 
}

Monday, 9 January 2017

Difference between Set, List and Map java Collections


      Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method
    Set set=new HashSet();
    Iterator iter = set.iterator();
    List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method
    List list = new ArrayList();
    Iterator iter = list.iterator();
    Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
    In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()
    Map m; // insert values
    Set s = m.keySet();
    // Get Map keys into the Set and then iterate this Set object normally
    // m.keySet() returns Set object with Map keys
    Iterator iter = s.iterator();

Sunday, 11 December 2016

write immutable class in Java with example

How to write immutable class in Java

Some points we need to follow, which helps to make a class immutable in Java :

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Class should be final in order to restrict sub-class for altering immutability of parent class.

So our immutable class have all private and final variables and a constructor to initialize the variables during object creation. All final variables can be initialized inside constructor only once during object creation that can't be changed latter. our immutable class does not provide setter method but have only getter method to access the initialized variables. 

Example

Simplest approach for making a class immutable, including it's making final class to avoid putting immutability at risk due to Inheritance and Polymorphism.



public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }

}

Singleton design pattern and preventing its cloning

Singleton :- Singleton design pattern is used to create only single object of the class. we can say to avoid the multiple object creation and limiting the number of objects to one. 

Prevent Object Cloning :- We can prevent the object cloning of singleton class by implementing the Cloneable interface and forcefully throw an exception 'throw new CloneNotSupportedException();' inside overridden clone() methods as written in below example-   

public class MySingletonTest implements Cloneable {

 private static MySingletonTest mSingletonTest = null;

 private MySingletonTest() {

  System.out.println("Sanjaya verma");

 }

 public static MySingletonTest getInstance() {

  if (mSingletonTest == null) {

   mSingletonTest = new MySingletonTest();

  }

  return mSingletonTest;

 }


 @Override
 protected Object clone() throws CloneNotSupportedException {
 // Here forcefully throw an exception to prevent the object cloning

  throw new CloneNotSupportedException();

  //return super.clone();

 }



 public static void main(String[] args) {

  MySingletonTest t1=new MySingletonTest(); 

  try {

       // call to overridden clone method which throw an exception

   MySingletonTest t2=(MySingletonTest)t1.clone(); 
   // compiler will not reach to this line.
   System.out.println(t2); 

  } catch (CloneNotSupportedException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

 }

}



Output-

Sanjaya verma

java.lang.CloneNotSupportedException

 at com.sanjay.java.interview.MySingletonTest.clone(MySingletonTest.java:21)

 at com.sanjay.java.interview.MySingletonTest.main(MySingletonTest.java:30)