Java 5 has introduced new concurrent API called "Executor frameworks" to make programmer life easy. It simplifies design and development of multi-thread applications. It consists of mainly Executor, ExecutorService interface and ThreadPoolExecutor class which implements both interfaces i.e. Executor and ExecutorService. ThreadPoolExecutor class provide the implementation of thread pool. We will understand more about it in the later part of the tutorial.

Why do we need Executor framework?

When we create a simple multi threading application, we create  Runnable objects and construct Thread object using Runnable, We need to create, execute and manage thread. It may be difficult for us to do that. Executor Framework does it for you. It is responsible for creating, executing and managing the thread and not only this, it improves the performance of the application too.
When you follow task per thread policy, you create a new thread for each task then if system is highly overloaded, you will get out of memory error and your system will fail. If you use ThreadPoolExecutor , you won't create thread for new task. You will assign task to a limited number of threads once thread completes one task, it will be given another task.

Core interface of Executor framework is Executor. It has a method called "execute".
public interface Executor {
   void execute(Runnable command);
}
There is another interface called ExecutorService which extends Executor interface. It can be termed as Executor that provides methods that can control termination and methods that can produce a Future for tracking the progress of one or more asynchronous tasks. It has method such as submit, shutdown, shutdownNow etc.
ThreadPoolExecutor is actual implementation of ThreadPool. It extends AbstractThreadPoolExecutor which implements ExecutorService interface. You can create ThreadPoolExecutor from factory methods of Executor class. It is recommended a way to get an instance of ThreadPoolExecutor.
There are 4 factory methods in Executors class which can be used to get an instance of ThreadPoolExecutor. We are using Executors' newFixedThreadPool to get an instance of ThreadPoolExecutor.
Example:
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
Here are four factory method present in Executors class.
newFixedThreadPool: This method returns thread pool executor whose maximum size(let's say n threads) is fixed.If all n threads are busy performing the task and additional tasks are submitted, then they will have to be in the queue until thread is available.
newCachedThreadPool: this method returns an unbounded thread pool. It doesn't have maximum size but if it has less number of tasks, then it will tear down unused thread. If thread has been unused for 1 mins(keepAliveTime), then it will tear it down.
newSingleThreadedExecutor: this method returns an executor which is guaranteed to use the single thread. 
newScheduledThreadPool: this method returns a fixed size thread pool that can schedule commands to run after a given delay, or to execute periodically.
Let's create a basic example of ThreadPoolExecutor and we will use newFixedThreadPool to create a instance of ThreadPoolExecutor.
Let's create a Task. Here Task will be to read different files and process them.
package org.arpit.java2blog.bean;

public class FetchDataFromFile implements Runnable{
 
 private final String fileName;
 
 public FetchDataFromFile(String fileName) {
  super();
  this.fileName = fileName;
 }
 
 @Override
 public void run() {
  try {
   System.out.println("Fetching data from "+fileName+" by "+Thread.currentThread().getName());
   Thread.sleep(5000); // Reading file
   System.out.println("Read file successfully: "+fileName+" by "+Thread.currentThread().getName());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 public String getFileName() {
  return fileName;
 }
}
Let's create ThreadPoolExecutor which will consume above task and process it.
package org.arpit.java2blog;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolExecutorMain {
 public static void main(String args[]) {
  // Getting instance of ThreadPoolExecutor using  Executors.newFixedThreadPool factory method
  ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
  for (int i = 0; i < 10; i++) {
   FetchDataFromFile fdff = new FetchDataFromFile("File " + i);
   System.out.println("A new file has been added to read : " + fdff.getFileName());
   // Submitting task to executor
   threadPoolExecutor.execute(fdff);
  }
  threadPoolExecutor.shutdown();
 }
}
When you run above program, you will get below output:
A new file has been added to read : File 0
A new file has been added to read : File 1
A new file has been added to read : File 2
Fetching data from File 0 by pool-1-thread-1
Fetching data from File 1 by pool-1-thread-2
A new file has been added to read : File 3
Fetching data from File 2 by pool-1-thread-3
A new file has been added to read : File 4
Fetching data from File 3 by pool-1-thread-4
A new file has been added to read : File 5
Fetching data from File 4 by pool-1-thread-5
A new file has been added to read : File 6
A new file has been added to read : File 7
A new file has been added to read : File 8
A new file has been added to read : File 9
Read file successfully: File 1 by pool-1-thread-2
Read file successfully: File 3 by pool-1-thread-4
Fetching data from File 5 by pool-1-thread-4
Read file successfully: File 4 by pool-1-thread-5
Read file successfully: File 2 by pool-1-thread-3
Read file successfully: File 0 by pool-1-thread-1
Fetching data from File 8 by pool-1-thread-3
Fetching data from File 7 by pool-1-thread-5
Fetching data from File 6 by pool-1-thread-2
Fetching data from File 9 by pool-1-thread-1
Read file successfully: File 5 by pool-1-thread-4
Read file successfully: File 7 by pool-1-thread-5
Read file successfully: File 6 by pool-1-thread-2
Read file successfully: File 8 by pool-1-thread-3
Read file successfully: File 9 by pool-1-thread-1

We have used new newFixedThreadPool, so when we have submitted 10 task, 5 new threads will be created and will execute 5 tasks. Other 5 tasks will wait in wait queue. As soon as any task will be completed by thread, another task will be picked by this thread and will execute it.

Using constructor of ThreadPoolExecutor: 

If you want to customize creation of ThreadPoolExecutor, you can use its constructors too.
   public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue ,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) ;
corePoolSize: corePoolSize is the number of threads to keep in the pool, even if they are idle
MaximumPoolSize: the maximum number of threads to allow in the pool
keepAliveTime: When you have more threads already available than corePoolSize, then keepAliveTime is time upto which that thread will wait for task before terminating.
unit: time unit is for keepAliveTime
workQueue: workQueue is the BlockingQueue which holds the tasks before execution.
threadFactory: Factory which is used to create a new Thread.
handler : RejectedExecutionHandler which is used in case execution is block or queue is full. Lets create a RejectedExecutionHandler for handling rejected task.
package org.arpit.java2blog.bean;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class RejectTaskHandler implements RejectedExecutionHandler{

 @Override
 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
  FetchDataFromFile ffdf=(FetchDataFromFile) r;
  System.out.println("Sorry!! We won't be able to read :"+ffdf.getFileName());  
 }
}
Lets change ThreadPoolExecutorMain.java to below code to make use of ThreadPoolExecutor constructor.
package org.arpit.java2blog.bean;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorMain {
 public static void main(String args[]) {
  
  // Wait queue is used to store waiting task
  BlockingQueue<Runnable> queue=new LinkedBlockingQueue<Runnable>(4);
  
  // Thread factory to create new threads
  ThreadFactory threadFactory=Executors.defaultThreadFactory();
  
  // Rejection handler in case task get rejected
  RejectTaskHandler rth=new RejectTaskHandler();
  // ThreadPoolExecutor constructor to create its instance
  ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 10L, TimeUnit.MILLISECONDS, queue,
    threadFactory,rth
    );
  for (int i = 1; i <= 10; i++) {
   FetchDataFromFile fdff = new FetchDataFromFile("File " + i);
   System.out.println("A new file has been added to read : " + fdff.getFileName());
   // Submitting task to executor
   threadPoolExecutor.execute(fdff);
  }
  threadPoolExecutor.shutdown();
 }
}
When you run above program, you will get below output:
A new file has been added to read : File 1
A new file has been added to read : File 2
A new file has been added to read : File 3
A new file has been added to read : File 4
Fetching data from File 1 by pool-1-thread-1
A new file has been added to read : File 5
A new file has been added to read : File 6
A new file has been added to read : File 7
Sorry!! We won't be able to read :File 7
A new file has been added to read : File 8
Sorry!! We won't be able to read :File 8
A new file has been added to read : File 9
Sorry!! We won't be able to read :File 9
A new file has been added to read : File 10
Sorry!! We won't be able to read :File 10
Fetching data from File 6 by pool-1-thread-2
Read file successfully: File 1 by pool-1-thread-1
Read file successfully: File 6 by pool-1-thread-2
Fetching data from File 2 by pool-1-thread-1
Fetching data from File 3 by pool-1-thread-2
Read file successfully: File 3 by pool-1-thread-2
Read file successfully: File 2 by pool-1-thread-1
Fetching data from File 4 by pool-1-thread-2
Fetching data from File 5 by pool-1-thread-1

If you notice here File 7, File 8, File 9 and File 10 got rejected. Lets understand why they got rejected. Max pool size in ThreadPoolExecutor's Constructor is 2, so when we submitted 10 tasks to thread pool, 2 threads got created and started processing 2 tasks and 4 tasks got queued in LinkedBlockingQueue, so once LinkedBlockingQueue became full, rest tasks got rejected.

How to decide the size of thread pool:

You should not hardcode size of thread pool. It should be provided by configuration or calculated from Runtime.availableProcessors.
Thread size should not be too big or too small. If you choose thread pool size that is too big, then it will overload the system and will not work properly. If you choose thread pool size too small, it will affect throughput and performance.

In this tutorial, we are going to see about Semaphore in java.
Semaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore.
  • acquire
  • release
acquire() method is used to get a permit and if no. of permits reaches max allowed permits then thread has to wait to get permit which will be released by some other thread by calling release() method.
Semaphores are generally used to restrict the number of threads to access resources.

Real time examples:

  • Semaphores can be used to restrict number of database connections at a time
  • Semaphores can also be used to bound any collection.

Example:

We will create a class BoundedArrayList which can have only 5 elements at a time. If any thread wants to add more element to the list,  thread will have to wait until any other thread remove elements from the list.
When we add an element to the list, we will call semaphore.acquire and when we remove an element from the list, we will call semaphore.release.
Create a class called BoundedArrayList.
package org.arpit.java2blog.bean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;

public class BoundedArrayList<T> {

 private final Semaphore semaphore;
 private List<T> arraylist;

 BoundedArrayList(int limit) {
  this.arraylist = Collections.synchronizedList(new ArrayList<T>());
  semaphore = new Semaphore(limit);
 }

 /*
  * Add element to the list and call semaphore.acquire method
  * */
 public boolean add(T t) throws InterruptedException {
  boolean added = false;
  semaphore.acquire();
  try {
   added = arraylist.add(t);
   return added;
  } finally {
   if (!added)
    semaphore.release();
  }

 }

 /*
  * remove element from the list and call semaphore.release method
  * */
 public boolean remove(T t) {
  boolean wasRemoved = arraylist.remove(t);
  if (wasRemoved)
   semaphore.release();
  return wasRemoved;
 }

 public void remove(int index) {
  arraylist.remove(index);
  semaphore.release();
 }

 public List<T> getArraylist() {
  return arraylist;
 }


 public Semaphore getSemaphore() {
  return semaphore;
 }
}
Create a main class BoundedArrayListMain.java
package org.arpit.java2blog.bean;

public class BoundedArrayListMain {

 public static void main(String[] args) throws InterruptedException {

  final BoundedArrayList<String> ba = new BoundedArrayList<String>(5);
  Runnable runnable1 = new Runnable() {

   @Override
   public void run() {
    try {
     ba.add("John");
     ba.add("Martin");
     ba.add("Adam");
     ba.add("Prince");
     ba.add("Tod");
     System.out.println("Available Permits : "+ba.getSemaphore().availablePermits());
     ba.add("Tony");
     System.out.println("Final list: "+ba.getArraylist());
    } catch (InterruptedException ie) {

    }
   }
  };
  Runnable runnable2 = new Runnable() {
   @Override
   public void run() {
    try {
     System.out.println("Before removing elements: "+ ba.getArraylist());
     Thread.sleep(5000);
     ba.remove("Martin");
     ba.remove("Adam");
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  };

  Thread t1 = new Thread(runnable1);
  Thread t2 = new Thread(runnable2);
  t1.start();
  t2.start();
 }

}
When you run above program, you will get below output:
Available Permits : 0
Before removing elements: [John, Martin, Adam, Prince, Tod]
Final list: [John, Prince, Tod, Tony]

Explanation:

  • We have created two thread t1 and t2.
  • t1 and t2 both share common list reference ba.
  • When t1 adds 5 elements to the list, available permits became 0. 
  • Now t1 waits for another thread to remove elements, so that semaphore have some available permits.
  • Another thread t2 removes elements from the list after waiting for 5 secs.
  • Once t2 removes elements, t1 adds "Tony" to list.

In this post, I am going to share java interview questions which are generally asked on immutable class. Immutable class is important topic as it deals with creation of thread safe class.
Here I am providing some important immutable class interview questions with answers.

1. What is immutable class?

Answer : Immutable objects are those objects whose state can not be changed once created. Class whose objects possess this characteristic can be termed as immutable class.
For example : String , Integer.

2. What are steps for creating an immutable class?

  • Make your class final : 
    If you make your class final, no class will be able to extend it, hence will not be able override methods of this class.
  • Declare all instance variable with private and final : 
    If you make instance variable private, no outside class will be able to access instance variables and if you make them final, you can not change it.
  • Say no to setter methods :
    Don't create setter method for any instance variables, hence there will be no explicit way to change state of instance variables.
  • Initialize all variables in constructor :
    You can initialize variables in constructor. You need to take special care while working with mutable object. You need to do deep copy in case of immutable objects.
  • Perform cloning of mutable objects while returning from getter method:
    If you return clone of object from getter method, it won't return original object, so your original object will remain intact.
    Read : Why String is immutable in java

3. Can you answer if below Employee class is immutable or not? If not what will you do to make it immutable?

package org.arpit.java2blog.bean;
import java.util.ArrayList;

public final class Employee {

 private final String name;
 private final ArrayList<String> addresses;
 public Employee(String name, ArrayList<String> addresses) {
  super();
  this.name = name;
  ArrayList<String> tempAdd=new ArrayList<String>();
  for (int i = 0; i < addresses.size(); i++) {
   tempAdd.add(addresses.get(i));
  }
  this.addresses = tempAdd;
 }
 
 public String getName() {
  return name;
 }
 public ArrayList<String> getAddresses() {
  return addresses;
 } 
}
Answer: 
Employee class is not an immutable class because you can still perform employee.getAddresses().add("New address") and it will be added to employee's addresses list.
You need to return clone of addresses list from getAddresses method ,so employee.getAddresses().add("New address")  won't impact employee's addresses list.
If you change above getAddresses() method to below method, Employee class will become immutable.
public ArrayList<String> getAddresses() {
  return (ArrayList<String>) addresses.clone();
 }

4. Can you provide example of immutable class?

Answer  : Yes. I have created  Country class which is immutable.
package org.arpit.java2blog.bean;

import java.util.ArrayList;

public final class Country {
    // declared private final instance variable
 private final String countryName;
 // Mutable object
 private final ArrayList<String> listOfStates;

 public Country(String countryName, ArrayList<String> listOfStates) {
  super();
  this.countryName = countryName;
  // Creating deep copy for mutable object
  ArrayList<String> tempList = new ArrayList<String>();

  for (int i = 0; i < listOfStates.size(); i++) {
   tempList.add(listOfStates.get(i));
  }
  this.listOfStates = tempList;
 }

 public String getCountryName() {
     // Do not need to do cloning as it is immutable object
  return countryName;
 }

 public ArrayList<String> getListOfStates() {
     // Returning cloned object 
  return (ArrayList<String>) listOfStates.clone();
 }
}

5. Do immutable classes thread safe? If yes then how?

Answer : 
Immutable classes are thread safe because you can not change state of immutable objects, so even if two thread access immutable object in parallel, it won't create any issue.

6. What precautions you need to take if you are working with mutable instance variables?

If you are working with mutable instance variable(addresses list in above Employee class) then do following:
  • Do deep copy mutable variable in constructor.
  • Return clone of instance variable from getter of that instance variable rather than actual variable.
You can read more about it at how to create immutable class in java.

7. Why immutable objects are considered to be good keys for HashMap?

Answer : Immutable object's hashcode won't change, so it makes key retrieval faster as you can cache different hashcode for different keys. In case of mutable object, hashcode may be dependent on mutable fields, if any value for these field changes, it might change hashcode, so you might not able to find your key in HashMap as hashcode is different now.

8. Can you give some good examples of immutable classes?

String, Integer, Long, Double, Character, Boolean etc and much more. Date is not an immutable class.

In this tutorial, we are going to see how to create immutable class in java.
Immutable class is class whose state can not be changed once created.
Example: String is best example for immutable class. Once you create a String, you can not change it.

Immutable class is very simple to understand, it has only one state. Immutable class is carefully instantiated by the constructor. Immutable classes are thread safe. This is biggest advantage of immutable class, you don't need to apply synchronization for immutable objects. Immutable class can be useful while putting object of immutable class in HashMap or it can be used for caching purpose because its value won't change.
Immutable objects are by default thread safe.

Steps for creating a immutable class:

  • Make your class final : 
    If you make your class final, no class will be able to extend it, hence will not be able override methods of this class.
  • Declare all instance variable with private and final : 
    If you make instance variable private, no outside class will be able to access instance variables and if you make them final, you can not change it.
  • Say no to setter methods :
    Don't create setter method for any instance variables, hence there will be no explicit way to change state of instance variables.
  • Initialize all variables in constructor :
    You can initialize variables in constructor. You need to take special care while working with mutable object. You need to do deep copy in case of imutable objects.
  • Perform cloning of mutable objects while returning from getter method:
    If you return clone of object from getter method, it won't return original object, so your original object will remain intact. I will explain this more in later part of this tutorial.
Read : Why String is immutable in java
Lets understand immutable class with a very simple example:
Lets create a simple class called Country.java.
package org.arpit.java2blog.bean;
import java.util.ArrayList;

public final class Country{
 
 private final String countryName; 
 private final ArrayList<String> listOfStates;
 
 public Country(String countryName,ArrayList<String> listOfStates) {
  super();
  this.countryName = countryName;
  this.listOfStates=listOfStates;
  
 }

 public String getCountryName() {
  return countryName;
 }

 public ArrayList<String> getListOfStates() {
  return  listOfStates;
 }
 
 public static void main(String args[])
 {
  ArrayList<String> listOfStates=new ArrayList<String>();
  listOfStates.add("Madhya Pradesh");
  listOfStates.add("Maharastra");
  listOfStates.add("Gujrat");
  
  Country country=new Country("India",listOfStates);
  System.out.println("Country : "+country.getCountryName());
  System.out.println("List of states : "+country.getListOfStates());
  // It will be added to the list because we did not use clone in getListOfStates
  country.getListOfStates().add("Kerala");
  // It will be added to the list because we did not use deep copy in constructor
  listOfStates.add("Rajasthan");
  System.out.println("Updated List of states : "+country.getListOfStates());
  
 }  
}
When you run the program, you will get below output:
Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat, Kerala, Rajasthan]
Above class is not immutable. There are two reasons for it :
  • We did not use clone in getListOfStates() method, so we are able to add "Kerala" to the listOfStates.
  • We did not do deep copy for listOfStates , so we are able to add "Rajasthan" to the list.
Lets use clone in getListOfStates() method and see the difference, just change getListOfStates() to below code:
public ArrayList<String> getListOfStates() {
  return  (ArrayList<String>) listOfStates.clone();
 }
when you run the program after making above changes, you will get below output:
Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat, Rajasthan]
If you notice, "Kerala" is not added to the list because we are returning clone of listOfStates in getListOfStates() method, so adding "Kerala" to country.getListOfStates() won't affect original list.
We are one step closed to immutable class now. 
Lets change constructor to make deep copy of listOfStates object.
public Country(String countryName, ArrayList<String> listOfStates) {
  super();
  this.countryName = countryName;
  ArrayList<String> tempList = new ArrayList<String>();

  for (int i = 0; i < listOfStates.size(); i++) {
   tempList.add(listOfStates.get(i));
  }
  this.listOfStates = tempList;
 }
Lets check the final class which we have created after doing above changes.
package org.arpit.java2blog.bean;

import java.util.ArrayList;

public final class Country {
    // declared private final instance variable
 private final String countryName;
 // Mutable object
 private final ArrayList<String> listOfStates;

 public Country(String countryName, ArrayList<String> listOfStates) {
  super();
  this.countryName = countryName;
  // Creating deep copy for mutable object
  ArrayList<String> tempList = new ArrayList<String>();

  for (int i = 0; i < listOfStates.size(); i++) {
   tempList.add(listOfStates.get(i));
  }
  this.listOfStates = tempList;
 }

 public String getCountryName() {
     // Do not need to do cloning as it is immutable object
  return countryName;
 }

 public ArrayList<String> getListOfStates() {
     // Returning cloned object 
  return (ArrayList<String>) listOfStates.clone();
 }

 public static void main(String args[]) {
  ArrayList<String> listOfStates = new ArrayList<String>();
  listOfStates.add("Madhya Pradesh");
  listOfStates.add("Maharastra");
  listOfStates.add("Gujrat");
  String countryName="India";
  Country country = new Country(countryName, listOfStates);
  System.out.println("Country : " + country.getCountryName());
  // Lets try to change local variable countryName
  countryName="China";
  System.out.println("Updated Country : " + country.getCountryName());
  System.out.println("List of states : " + country.getListOfStates());
  // It will  not be added to the list because we are using clone in
  // getListOfStates
  country.getListOfStates().add("Kerala");
  // It will not be added to the list because we are using deep copy in
  // constructor
  listOfStates.add("Rajasthan");
  System.out.println("Updated List of states : " + country.getListOfStates());

 }

}
When you run above program, you will get below output:
Country : India
Updated Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat]

Country class is immutable class now. As you can see, we are doing deep copy for listOfStates, so "Rajasthan" will not be added to the listOfStates.

I hope it will help you to create immutable class in java.

In this tutorial, we are going to see Retrofit Android tutorial to get data from server.
In previous post, we have seen android JSON parsing tutorial which was very simple.
If you are not aware about Retrofit, it is android http library used to handle HTTP request.You can treat it as a replacement of AsyncTask in previous tutorial.

Why to use Retrofit rather than Volley or AsyncTask.

It is better than Volley and AsyncTask. It takes care of HTTP call, JSON parsing, efficient network management. Retrofit has all the features which you need to call web services. You will directly get Response which you can use to populate data.

Example :

I have already implemented restful webservices json example. I am going to use same json response for rendering it in custom listview.
You can use below link.
https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json
You will get below Json response from above URL:
[  
   {  
      "id":1,
      "countryName":"India"
   },
   {  
      "id":4,
      "countryName":"China"
   },
   {  
      "id":3,
      "countryName":"Nepal"
   },
   {  
      "id":2,
      "countryName":"Bhutan"
   }
]
We are getting above JSONArray from rest web service. If you are not familiar with JSON, you can go through Json tutorial. We are going to render above JSON response to android custom listview as below:

Lets code this example now:

Source code:

Step 1 :Creating Project

Create an android application project named "RetrofitAndroidExample".

Step 2 : Add Retrofit and json gradle dependency

For using Retrofit library, we need to add Retrofit and volley dependency. Your build.gradle (Module : app )will look as below
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.java2blog.retrofitandroidexample"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    // retrofit, gson
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    testCompile 'junit:junit:4.12'
}


Step 3 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="10dp"
    tools:context="com.java2blog.retrofitandroidexample.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetching countries data"
        android:id="@+id/btnSubmit"
        />

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnSubmit"
        />
</RelativeLayout>

We have one button and listview. When you click the button, we are going to populate data in listview by calling restful web services and render it on the listview.

Step 4: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "row_item.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="30dp"
        android:textColor="#1E90FF"
        android:id="@+id/textViewId"
        android:layout_row="0"
        android:layout_column="1" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:id="@+id/textViewCountry"
        android:layout_row="1"
        android:layout_column="1" />
</GridLayout>

Step 5 : Creating model object Country :

If you notice, we are getting Json array from restful web service which has 4 items. Each item have two attributes id and countryName. We are going to create country object for each item.
package com.java2blog.androidrestjsonexample;
public class Country{
    int id;
    String countryName;

    public Country(int i, String countryName) {
        super();
        this.id = i;
        this.countryName = countryName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Step 6:  Creating BaseAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
package com.java2blog.androidrestjsonexample;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.java2blog.androidrestjsonexample.Country;
import com.java2blog.androidrestjsonexample.R;

import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {


    private Activity context;
    ArrayList<Country> countries;


    public CustomCountryList(Activity context, ArrayList<Country> countries) {
     //   super(context, R.layout.row_item, countries);
        this.context = context;
        this.countries=countries;

    }

    public static class ViewHolder
    {
        TextView textViewId;
        TextView textViewCountry;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row=convertView;

        LayoutInflater inflater = context.getLayoutInflater();
        ViewHolder vh;
        if(convertView==null) {
            vh=new ViewHolder();
            row = inflater.inflate(R.layout.row_item, null, true);
            vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
            vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
            // store the holder with the view.
            row.setTag(vh);
        }
        else {
            vh = (ViewHolder) convertView.getTag();
        }

        vh.textViewCountry.setText(countries.get(position).getCountryName());
        vh.textViewId.setText(""+countries.get(position).getId());

        return  row;
    }

    public long getItemId(int position) {
        return position;
    }

    public Object getItem(int position) {
        return position;
    }

    public int getCount() {

        if(countries.size()<=0)
            return 1;
        return countries.size();
    }
}
This class is used to populating data for ListVIew. getView method is get called for drawing each row.

Step 7 : Creating interface for making HTTP call using Retrofit.

We need to create an interface for making HTTP calls.
package com.java2blog.retrofitandroidexample;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.GET;

public interface CountryArrayAPI {

    /* @GET url is after Base_URL.
       We are going to get List of country as response.
    */
    @GET("/arpitmandliya/AndroidRestJSONExample/master/countries.json")
    public Call<List<Country>> getCountries();
}
We have defined get request in above interface. We do not have to include base url, it is part after base url which we have use. We are going to get List of countries as response here.

Step 8 : Creating MainActivity

Steps for Retrofit call :
  • Create retrofit instance using base url. Retrofit will implicitly use gson to convert JSON to corresponding object. You need to define gson library explicitly in Retrofit 2.0 
    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
  • Create api with retrofit's create method and call getCountries method.
     CountryArrayAPI api = retrofit.create(CountryArrayAPI.class);
    Call<List<Country>> call = api.getCountries();
    
  • Enqueue the request and onResponse will get called if your call is successful else onFailure will get called.
Change src/main/packageName/MainActivity.java as below:
package com.java2blog.retrofitandroidexample;

import android.util.Log;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends AppCompatActivity {

    private Button btnSubmit;
    String responseText;
    Activity activity;
    ArrayList<Country> countries=new ArrayList<Country>();
    private ProgressDialog progressDialog;
    ListView listView;

    //Base URL of our web service
    public static final String BASE_URL = "https://cdn.rawgit.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        listView = (ListView) findViewById(android.R.id.list);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countries.clear();

                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Fetching countries data");
                progressDialog.setCancelable(false);
                progressDialog.show();
                //Call WebService
                getWebServiceResponseData();
            }
        });
    }

    protected Void getWebServiceResponseData() {

        //Creating Retrofit rest adapter
         Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //Creating an object of our api interface
        CountryArrayAPI api = retrofit.create(CountryArrayAPI.class);
        Call<List<Country>> call = api.getCountries();

        call.enqueue(new Callback<List<Country>>() {

            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {

                try {

                    countries= (ArrayList)response.body();

                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                    // For populating list data
                    CustomCountryList customCountryList = new CustomCountryList(activity, countries);
                    listView.setAdapter(customCountryList);

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            Toast.makeText(getApplicationContext(),"You Selected "+countries.get(position).getCountryName()+ " as Country",Toast.LENGTH_SHORT).show();        }
                    });
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }
            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) {
                    Log.d("Failure",t.toString());
            }
        });
        return null;
    }
}

Step 8: Add internet permission in AndroidManifest.xml

Copy following code:
<uses-permission android:name="android.permission.INTERNET" />

Put it in AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <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>
    </application>

</manifest>
Done, we have added internet permission to AndroidManifest.xml. Your application must be able to access internet now.

Step 9 : Running the app 

When you run the app, you will get below screen:


When you click on above button, you will get below screen.


We are done with Android Retrofit tutorial. If you are facing any issue, please comment.

In this tutorial, we are going to see Android JSON parsing tutorial using Volley.
In previous post, we have seen android JSON parsing tutorial which was very simple. In this tutorial, we are going to use external library Volley for sending HTTP request. You can treat it as a replacement of AsyncTask in previous tutorial.

Why to use Volley rather than AsyncTask.

  • Less complex
  • Efficient network management.
  • Easily customisable

Example :

I have already implemented restful webservices json example. I am going to use same example for implementation of restful web services.
If you are going to deploy above web service then use below url to fetch json data
http://192.168.2.22:8080/JAXRSJsonExample/rest/countries
Here 192.168.2.22 is IP address of my machine. Once you implement this web services on your machine, you should replace it with your ip address.
If you don't want to implement rest web service yourself and want below json response. You can use below link.
https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json
You will get below Json response from above URL:
[  
   {  
      "id":1,
      "countryName":"India"
   },
   {  
      "id":4,
      "countryName":"China"
   },
   {  
      "id":3,
      "countryName":"Nepal"
   },
   {  
      "id":2,
      "countryName":"Bhutan"
   }
]
We are getting above JSONArray from rest web service. If you are not familiar with JSON, you can go through Json tutorial. We are going to render above JSON response to android custom listview as below:

Lets code this example now:

Source code:

Step 1 :Creating Project

Create an android application project named "JSONPasingUsingVolley".

Step 2 : Add Volley gradle dependency

For using Volley library, we need to add volley dependency "compile 'com.mcxiaoke.volley:library:1.0.19'"in build.gradle(Module : app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.java2blog.jsonparsingusingvolley"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    testCompile 'junit:junit:4.12'
}

Step 3 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="10dp"
    tools:context="com.java2blog.androidrestjsonexample.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetching countries data"
        android:id="@+id/btnSubmit"
        />

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnSubmit"
        />
</RelativeLayout>

We have one button and listview. When you click the button, we are going to populate data in listview by calling restful web services and render it on the listview.

Step 4: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "row_item.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="30dp"
        android:textColor="#1E90FF"
        android:id="@+id/textViewId"
        android:layout_row="0"
        android:layout_column="1" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:id="@+id/textViewCountry"
        android:layout_row="1"
        android:layout_column="1" />
</GridLayout>

Step 5 : Creating model object Country :

If you notice, we are getting Json array from restful web service which has 4 items. Each item have two attributes id and countryName. We are going to create country object for each item.
package com.java2blog.androidrestjsonexample;
public class Country{
    int id;
    String countryName;

    public Country(int i, String countryName) {
        super();
        this.id = i;
        this.countryName = countryName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Step 6:  Creating BaseAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
package com.java2blog.androidrestjsonexample;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.java2blog.androidrestjsonexample.Country;
import com.java2blog.androidrestjsonexample.R;

import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {


    private Activity context;
    ArrayList<Country> countries;


    public CustomCountryList(Activity context, ArrayList<Country> countries) {
     //   super(context, R.layout.row_item, countries);
        this.context = context;
        this.countries=countries;

    }

    public static class ViewHolder
    {
        TextView textViewId;
        TextView textViewCountry;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row=convertView;

        LayoutInflater inflater = context.getLayoutInflater();
        ViewHolder vh;
        if(convertView==null) {
            vh=new ViewHolder();
            row = inflater.inflate(R.layout.row_item, null, true);
            vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
            vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
            // store the holder with the view.
            row.setTag(vh);
        }
        else {
            vh = (ViewHolder) convertView.getTag();
        }

        vh.textViewCountry.setText(countries.get(position).getCountryName());
        vh.textViewId.setText(""+countries.get(position).getId());

        return  row;
    }

    public long getItemId(int position) {
        return position;
    }

    public Object getItem(int position) {
        return position;
    }

    public int getCount() {

        if(countries.size()<=0)
            return 1;
        return countries.size();
    }
}
This class is used to populating data for ListVIew. getView method is get called for drawing each row.

Step 7 : Creating MainActivity

We are going to use JSONArrayRequest class of volley library.
JsonArrayRequest req = new JsonArrayRequest(jsonURl,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {... , new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {...)
It has three parameters.
  • rest web services url which returns JSONArray response.
  • Passing Listener which has method called onResponse that will get called when we get response from rest url.
  • Passing ErrorListener which has method called onErrorResponse that will get called when we get any error while executing the rest web service url.

You can also use JsonObjectRequest or StringRequest from volley class depend on your need.

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.jsonparsingusingvolley;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity {

    private Button btnSubmit;
    String responseText;
    Activity activity;
    ArrayList<Country> countries=new ArrayList<Country>();
    private ProgressDialog progressDialog;
    ListView listView;

    // In case if you deploy rest web service, then use below link and replace below ip address with yours
    //http://192.168.2.22:8080/JAXRSJsonExample/rest/countries
    
    //Direct Web services URL
    private String path = "https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        listView = (ListView) findViewById(android.R.id.list);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countries.clear();

                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Fetching conntry data");
                progressDialog.setCancelable(false);
                progressDialog.show();
                //Call WebService
                getWebServiceResponseData();
            }
        });
    }

    protected Void getWebServiceResponseData() {
            JsonArrayRequest req = new JsonArrayRequest(jsonURl,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.d(TAG, response.toString());
                            if (progressDialog.isShowing())
                                progressDialog.dismiss();

                            // Parsing json response and iterate over each JSON object
                            Log.d(TAG, "data:" + responseText);
                            try {

                                for (int i = 0; i < response.length(); i++) {
                                    JSONObject jsonobject = response.getJSONObject(i);
                                    int id = jsonobject.getInt("id");
                                    String country = jsonobject.getString("countryName");
                                    Log.d(TAG, "id:" + id);
                                    Log.d(TAG, "country:" + country);
                                    Country countryObj = new Country(id, country);
                                    countries.add(countryObj);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Error: " + e.getMessage(),
                                        Toast.LENGTH_LONG).show();
                            }

                            CustomCountryList customCountryList = new CustomCountryList(activity, countries);
                            listView.setAdapter(customCountryList);

                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                    Toast.makeText(getApplicationContext(),"You Selected "+countries.get(position).getCountryName()+ " as Country",Toast.LENGTH_SHORT).show();        }
                            });
                         }
                        },   new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
                            }

                        });
                        RequestQueue requestQueue = Volley.newRequestQueue(this);
                        requestQueue.add(req);
            return null;
        }
    }

Step 8: Add internet permission in AndroidManifest.xml

Copy following code:
<uses-permission android:name="android.permission.INTERNET" />

Put it in AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <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>
    </application>

</manifest>
Done, we have added internet permission to AndroidManifest.xml. Your application must be able to access internet now.

Step 9 : Running the app 

When you run the app, you will get below screen:


When you click on above button, you will get below screen.


We are done with Android JSON parsing tutorial using Volley. If you are facing any issue, please comment.

I have already shared about Whizlabs OCAJP 8 exam simulator in my previous post. I have looked further to OCPJP 8 content of whizlabs and found it useful too, hence sharing it.
OCPJP is tougher exam than OCAJP hence you will need more practice to pass it than OCAJP.

What is OCPJP 8?

OCPJP 8 stands for Oracle Certified Professional, Java SE 8 Programmer. It is the advance level of certification in the Oracle Java certification path. This exam checks the advance knowledge on the Java programming. If You have already cleared OCAJP, this is next level exam for you. If you have already passed exam on Java 5 or Java 6 and want to upgrade your knowledge for Java 8, this is good option for you.

Exam Details – OCPJP 8

Exam Number : 1Z0-809
Certification Name : Oracle Certified Professional, Java SE 8 Programmer.
Duration : 150 minutes
Number of Questions : 85
Passing Score : 65% (50 out of 85)
Format : Multiple Choice
Price : It varies for each country and location. Please check with your nearest prometric centers.

Why Whizlabs OCPJP 8?

As I have already shared about Whizlabs simulator in previous post but I would like to highlight few points again.
  • Lot of practice questions : It provides you lot of practice question and it is needed as it has lots of new topics such as lambda expressions and as this exam is tougher than OCAJP, you definitely need more practice for it.
  • Identify your weak area : It also provides break down for each topics such as Java basics, handling exceptions etc., so you can identify your weak area and practice it more.
  • Get detailed explanation : You will also get detailed explanation for each question which will help you to understand java concepts better.
  • Lifetime access : Once you subscribe , exams can be accessed for life time with their login details.
Here I am sharing some screenshots of tests provided by Whizlabs.
Whizlabs test 1


You can create your own custom test too based on topics 


Sample Question:


Sample question with detailed explanation:

In the end, if you are interested in OCPJP 8  certification and looking for good exam simulator to practice, go with Whizlabs.

Some Additional Information for OCPJP Preparation 

Here I would like to share some of the useful resources that will help you to prepare for the OCPJP exam.
Official Site for OCPJP Exam 
OCPJP forums 
How to prepare for OCPJP exam? 
What are the best books for preparing OCPJP exam? 
Whizlabs Mock Exams for OCPJP 8 
Whizlabs Mock Exams for OCPJP 7

In this tutorial, we are going to integrate android with restful web services which return json as response.
So we are going to get json from restful web services and then render json response to android custom listview.

Example :

I have already implemented restful webservices json example. I am going to use same example for implementation of restful web services.
If you are going to deploy above web service then use below url to fetch json data
http://192.168.2.22:8080/JAXRSJsonExample/rest/countries
Here 192.168.2.22 is IP address of my machine. Once you implement this web services on your machine, you should replace it with your ip address.
If you don't want to implement rest web service yourself and want below json response. You can use below link.
https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json
You will get below Json response from above URL:
[  
   {  
      "id":1,
      "countryName":"India"
   },
   {  
      "id":4,
      "countryName":"China"
   },
   {  
      "id":3,
      "countryName":"Nepal"
   },
   {  
      "id":2,
      "countryName":"Bhutan"
   }
]
We are getting above Json array from rest web service. If you are not familiar with JSON, you can go through Json tutorial. We are going to render above JSON response to android custom listview as below:

Lets code this example now:

Source code:

Step 1 :Creating Project

Create an android application project named "AndroidRestJsonExample".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="10dp"
    tools:context="com.java2blog.androidrestjsonexample.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetching countries data"
        android:id="@+id/btnSubmit"
        />

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnSubmit"
        />
</RelativeLayout>

We have one button and listview. When you click the button, we are going to populate data in listview by calling restful web services and render it on the listview.

Step 3: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "row_item.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="30dp"
        android:textColor="#1E90FF"
        android:id="@+id/textViewId"
        android:layout_row="0"
        android:layout_column="1" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:id="@+id/textViewCountry"
        android:layout_row="1"
        android:layout_column="1" />
</GridLayout>

Step 4 : Creating model object Country :

If you notice, we are getting Json array from restful web service which has 4 items. Each item have two attributes id and countryName. We are going to create country object for each item.
package com.java2blog.androidrestjsonexample;
public class Country{
    int id;
    String countryName;

    public Country(int i, String countryName) {
        super();
        this.id = i;
        this.countryName = countryName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Step 5 :  Creating BaseAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
package com.java2blog.androidrestjsonexample;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.java2blog.androidrestjsonexample.Country;
import com.java2blog.androidrestjsonexample.R;

import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {


    private Activity context;
    ArrayList<Country> countries;


    public CustomCountryList(Activity context, ArrayList<Country> countries) {
     //   super(context, R.layout.row_item, countries);
        this.context = context;
        this.countries=countries;

    }

    public static class ViewHolder
    {
        TextView textViewId;
        TextView textViewCountry;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row=convertView;

        LayoutInflater inflater = context.getLayoutInflater();
        ViewHolder vh;
        if(convertView==null) {
            vh=new ViewHolder();
            row = inflater.inflate(R.layout.row_item, null, true);
            vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
            vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
            // store the holder with the view.
            row.setTag(vh);
        }
        else {
            vh = (ViewHolder) convertView.getTag();
        }

        vh.textViewCountry.setText(countries.get(position).getCountryName());
        vh.textViewId.setText(""+countries.get(position).getId());

        return  row;
    }

    public long getItemId(int position) {
        return position;
    }

    public Object getItem(int position) {
        return position;
    }

    public int getCount() {

        if(countries.size()<=0)
            return 1;
        return countries.size();
    }
}
This class is used to populating data for ListVIew. getView method is get called for drawing each row.

Step 6 : Creating MainActivity

We are going to create a addition inner class GetServerData which extends AsyncTask. This class will make https call in background thread.
Here are three methods which you may need to implement while using AsyncTask.
  • onPreExecute() : This method will get called before making HTTP call. We are initializing ProgressDialog here.
  • doInBackground : We are going to make HTTP call in this method. We have use HttpURLConnection class to make HTTP call. You can not access any UI elements while executing this method
  • onPostExecute  : This executes after execution of doInBackground method. In this method, we are going to create CustomCountryList object and populate listview data.
Change src/main/packageName/MainActivity.java as below:
package com.java2blog.androidrestjsonexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity {

    private Button btnSubmit;
    String responseText;
    StringBuffer response;
    URL url;
    Activity activity;
    ArrayList<Country> countries=new ArrayList<Country>();
    private ProgressDialog progressDialog;
    ListView listView;
    // In case if you deploy rest web service, then use below link and replace below ip address with yours
    //http://192.168.2.22:8080/JAXRSJsonExample/rest/countries
    
    //Direct Web services URL
    private String path = "https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            activity = this;
            btnSubmit = (Button) findViewById(R.id.btnSubmit);
            listView = (ListView) findViewById(android.R.id.list);
            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    countries.clear();
                    //Call WebService
                    new GetServerData().execute();
                }
            });
        }

        class GetServerData extends AsyncTask
        {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Fetching conntry data");
                progressDialog.setCancelable(false);
                progressDialog.show();

            }

            @Override
            protected Object doInBackground(Object[] objects) {
                return getWebServiceResponseData();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);

                // Dismiss the progress dialog
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
                // For populating list data
                CustomCountryList customCountryList = new CustomCountryList(activity, countries);
                listView.setAdapter(customCountryList);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        Toast.makeText(getApplicationContext(),"You Selected "+countries.get(position).getCountryName()+ " as Country",Toast.LENGTH_SHORT).show();        }
                });
            }
        }
        protected Void getWebServiceResponseData() {

            try {

                url = new URL(path);
                Log.d(TAG, "ServerData: " + path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("GET");

                int responseCode = conn.getResponseCode();

                Log.d(TAG, "Response code: " + responseCode);
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    // Reading response from input Stream
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String output;
                    response = new StringBuffer();

                    while ((output = in.readLine()) != null) {
                        response.append(output);
                    }
                    in.close();
                }}
             catch(Exception e){
                    e.printStackTrace();
            }

                responseText = response.toString();
                //Call ServerData() method to call webservice and store result in response
              //  response = service.ServerData(path, postDataParams);
                Log.d(TAG, "data:" + responseText);
                try {
                    JSONArray jsonarray = new JSONArray(responseText);
                    for (int i = 0; i < jsonarray.length(); i++) {
                        JSONObject jsonobject = jsonarray.getJSONObject(i);
                        int id = jsonobject.getInt("id");
                        String country = jsonobject.getString("countryName");
                        Log.d(TAG, "id:" + id);
                        Log.d(TAG, "country:" + country);
                        Country countryObj=new Country(id,country);
                        countries.add(countryObj);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
    }

Step 7: Add internet permission in AndroidManifest.xml

Copy following code:
<uses-permission android:name="android.permission.INTERNET" />

Put it in AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <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>
    </application>

</manifest>
Done, we have added internet permission to AndroidManifest.xml. Your application must be able to access internet now.

Step 8 : Running the app 

When you run the app, you will get below screen:


When you click on above button, you will get below screen.


We are done with Android Restful web services json example. If you are facing any issue, please comment.

In this article I am going to write about the various AWS certifications and suitable certifications for your profile. Most of the organizations are migrating their applications to the cloud environment, which rises the demand for cloud engineers.
The advantage of cloud is that you can minimize the cost and time for maintenance by 1/10 of your actual numbers. The market leaders in cloud computing is Amazon, Microsoft and Google. However, Amazon has surpassed everyone by moving ahead with lot of innovation in the cloud computing market.
If you are planning to learn cloud computing, then Amazon Web Services (AWS) is the clear winner. There is growing demand for the AWS certified engineers.

AWS Certifications 

AWS has five certifications and three beta certifications. These certifications are classified as Associate, Professional and Specialty certifications. Associate certifications are entry level or junior certifications, Professional certifications are considered as advanced or expert level certifications. Whereas Specialty certifications (these certifications are recently launched by Amazon) are focus on specific knowledge areas like Big Data, Security, etc. within AWS environment.

Here is the list of certification offered by Amazon:

Associate Certifications

• Solutions Architect Associate
• Developer Associate
• SysOps Administrator

Associate Professional Certifications

• Solutions Architect Professional
• Developer Engineer Professional

Specialty Certifications

• Advanced Networking Specialty
• Security Specialty
• Big Data Specialty

Why should I pass AWS Certifications? 

Here are some of the reasons why AWS certified employees can get more salary:
• It is obvious that cloud computing is becoming very hot and now most of the enterprise applications moved to cloud. So, every company has dire need of cloud engineers. AWS is the leader in cloud computing.
• In the recent announcement, Amazon has mandated that every AWS technology partner has to demonstrate their capability by adding certified engineers to their companies. It explicitly shows that just having the certification itself may attract the employers to hire you.
• There is a huge demand for the AWS developers, but there is not enough skilled resources in the market. That is a huge gap that has to be filled. It is apparent that AWS certified developers will be paid well by the companies.

Which is the suitable exam for you?

Note that all the associate exams have no prerequisite. So, anyone can write the exams. But, professional and specialty exams have the prerequisite of associate level exams. It is mandatory for you to start with the associate level exams.
• If you are looking for just the knowledge on AWS and learning all the concepts in AWS, then Solutions Architect Associate exam is the one which you have to start the preparation. This exam covers all the topics in AWS and mainly focus on the knowledge level and not focused on the coding part. If you are a developer and want to get the knowledge on coding part, then you would start with Developer Associate exam.
• Solutions Architect Associate and Developer Associate exams have more than 50% of objectives overlap. Solutions Architect is the lower level and Developer exam is the higher level with respect to the coverage of topics.
• SysOps Administrator is the toughest exam in the associate level. This exam would test your knowledge on deployment and real time implementation for all the services. You can try this exam if you have good experience with AWS otherwise it would be difficult for you to pass the exam without hands on experience.
• All the professional level exams are tough and you should have good experience to pass the exam. There is no other short cut to get through because most of the questions asked in the exams are real time scenario based. Solutions Architect Professional exam has the prerequisite of Solutions Architect Associate exam. DevOps Engineer Professional exam has the prerequisite of either Developer Associate or SysOps Administrator Associate exam.

What is the cost? 

• All the associate level exams cost $150
• All the professional level exams cost $300
The cost is same across the countries. There is no distinction mentioned in the AWS website.

Associate Exam Information 

It seems to be there is no fixed guideline for the number of questions and duration set for the exam. Amazon keeps changing the number of questions, duration and passing score. As of now, the following are the most likely you will get in the exam.
• Number of Questions : 60 Multiple Choice Questions
• Duration : 80 Minutes
• Passing Score : 65%

 Professional Exam Information

Here is the exam summary for the professional level exams.
• Number of Questions : 80 Multiple Choice Questions
• Duration : 170 Minutes
• Passing Score : 65%

How to register for the AWS certification exam? 

Amazon has tied up with WebAssessor.com for conducting the exams. You can directly register for any of the AWS certification exam using the above link and schedule the exam. This facility is available in all the countries across the world.

Additional Resources for preparing for AWS Certifications 

https://aws.amazon.com/faqs/
Amazon Certification Preparation Guide
How to prepare for Solutions Architect Associate certification exam?
Practice Questions for AWS Certifications
 

Java tutorial for beginners Copyright © 2012