In this tutorial, we will see how to check if number is power of two.
There are many approaches to check if number is power of two or not.

Approach 1:

It is very easy and straight forward approach.
  • Run a while loop which checks for condition if n is even number (n%2==0).
  • If n is even then divide it by 2 in each iteration.
  • When you get out of while loop and n is equal to 1 then number is power of two,
  • If number is not equal to 1 then number is not power of two.
public static boolean powerOfTwoGeneral(int n)
 {
  while(n%2==0)
  {
   n=n/2;
  }
  if(n==1)
  {
   return true;
  }
  else
  {
   return false;
  }
 }

Approach 2:

We can use bitwise and operator to check if number is power of two or not.
public static boolean powerOfTwoBitwise(int n)
 {
  return (n & n-1)==0;
 }
It will a very simple way to check if number is power of two. Let's see how it works.
Let's say n is 8. Its binary representation will be : 1000.
binary represetation of 7 will be : 0111.
           1 0 0 0
       & 0 1 1 1
         ----------
          0 0 0 0
         ----------
If number is power of 2, then it will have only one bit set to "1".
For example:
8 :   1000
32 : 100000

Similarly when you  check binary form of 7 and 31, it will have all the bits set to "1"
7 :   111
31:  11111
so if you apply bitwise & operator on n and n-1 and result is 0. It means number is power of two.

Java program to check if number is power of two:

package org.arpit.java2blog;

public class PowerOfTwoMain {

 public static void main(String[] args) {
  System.out.println("128 is power of two : "+powerOfTwoGeneral(128));
  System.out.println("64 is power of two : "+powerOfTwoBitwise(64));
  System.out.println("22 is power of two : "+powerOfTwoBitwise(22));
  System.out.println("22 is power of two : "+powerOfTwoGeneral(22));
 }
 // Approach 1
 public static boolean powerOfTwoGeneral(int n)
 {
  while(n%2==0)
  {
   n=n/2;
  }
  if(n==1)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
 // Approach 2
 public static boolean powerOfTwoBitwise(int n)
 {
  return (n & n-1)==0;
 }

}

When you run above code, you will get below results
128 is power of two : true
64 is power of two : true
22 is power of two : false
324 is power of two : false

In my previous articles, I have written about solutions architect exam and list of AWS certifications. AWS is the market leader in the cloud computing platform. If you are planning to switch your career to cloud computing, then AWS is the right place to start your learning process. Microsoft Azure is the only competitor for the AWS platform.
We are going to see a lot of new changes to cloud computing and AWS in the year 2017. Serverless computing is the latest trend in the cloud. Amazon Lambda is an example for the serverless computing and it saves a lot of cost for the companies to move and run their code in the cloud.

AWS certifications are most valuable in the market. With the current demand for cloud engineers across the companies, there is a good amount of requirements seek AWS certifications. I would continue to write in my blog about the AWS certifications and how to prepare for the certifications. If you have any questions, please write it in the comments section.
In this article, we will explain you step by step process on how to effectively prepare for the AWS Certified SysOps Administrator Associate certification exam. This is the toughest exam in the associate level exam. It is a good idea to start from Developer Associate Exam if you are planning to prepare for all the associate level certifications.
The order of the AWS certification preparation should be:
Developer Associate
Solutions Architect Associate
SysOps Administrator Associate
Solutions Architect Professional
DevOps Engineer Professional
We will explore the best approach for studying for the SysOps Administrator Associate certification exam. One of the challenges with preparing for AWS certification is that there is no official study guide for the preparation. You have to mostly depend on the official documentation that are available with AWS website. Also, Amazon keeps adding new services frequently that also will be added to the exams. It is good enough to read the official documentation from Amazon website and practice the questions to pass the exam.

AWS Website:

This will be the first place to start your certification journey. The official website would have all the useful and important details about the certification in the central place. You have to visit the official link for the certification details. You will get all the details like blueprint, sample questions, exam information, video tutorials, etc. Keep this link bookmarked and refer whenever you have any questions about the scope of exam and list of topics that are covered in the exam.
I assume that you have already created a free tier with AWS account. This will help you to use for practice the services.

Exam BluePrint:

The exam blueprint is the official syllabus for the exam. This blueprint explains what are the concepts that are covered in the exam and breakup of the sections and marks that are expected from the each section. This should be the first document one should read for preparing for the exam.
Here is the snapshot of how blueprint shows the list of topics and proportion of exam questions. This would help you lot to prepare for the exam. If you look at the below snapshot, SysOps Administrator exam has the equal amount of questions from all the topics. There are total 7 topics are covered in this exam.

You can also refer the detailed chapters / contents that will be tested in the exam. If you look at the below snapshot, it clearly shows that what are the concepts that are tested in the exam. Note that SysOps exam would not check only the theoretical concepts, more number of questions will be asked in the scenario based real time questions. You should have good experience to answer those questions. 

Whitepapers

This is the collection of documents that offers more in-depth information about each service. This whitepapers contains very useful information about the services. There are several whitepapers available on this page, but you will not be able to read all the documents for the exam. This page also keeps updated with latest whitepapers and reports. Based on the exam topics, you can select few whitepapers and read them.
The following are the important whitepapers that are must read for the exam. Note that this list for preparing the SysOps administrator exam. Other exams will have some other recommended whitepapers.
It is important to read the whitepapers multiple times to get good understanding of the concepts. It is often reported by the exam takers that most of the questions are asked from the whitepapers and that helped them to answer the questions. Note that SysOps exam would expect you to answer the more scenario based questions and deployment related questions.

Practice Questions

Once you have gone through the required study materials, FAQs and whitepapers, then it is the time to take the practice questions. AWS provides few samples questions on the website. But, that is not sufficient for the exam. You have to purchase a good quality practice questions in the market to pass the exam. Whizlabs is one of the most popular practice questions for the AWS certification exam. You can buy their 420 questions and practice well.

Hands on practice

Hands-on experience is definitely the best and efficient way to learn AWS concepts. Nothing can give you more confidence in picking the right answer like having done it yourself. This is one of the most
Unfortunately, this also highlights one of the drawbacks of this kind of certification - sometimes the exams lag behind the real-world. There are some things that the AWS services now do things that aren't reflected in the certification exam.
If you don't have the benefit of using AWS at work, create a new AWS account (i.e. using a new email address) and make the most of the free usage tier. Just set up a billing alarm to send you an email when you are in danger of being charged too much, and you can't go to wrong.

About The Exam

The exam will have 55 multiple choice questions with an 80 minute time limit. Most questions would be single-answer responses, but some are multiple-answer responses. The exact pass mark does change without notice, according to statistical analysis (see the FAQ). 

Also, you have to sign a NDA agreement before taking the exam. You are not allowed to write or talk about the exam details. It is against the policy. So, the practice questions offered by various training are based on the syllabus topics that is shared by Amazon.

Additional Resources

Here is some useful information that would be helpful for you to prepare for this certification exam:
     • Official Link
I hope this article is very informative to understand the basic details that are required to prepare for the AWS Certified SysOps Administrator Associate certification exam. If you have any questions, please write it in the comments section.

Summary

I hope this article is informative and useful for you to prepare for the AWS Certified SysOps Administrator Associate exam. I have explained the important source of information required for preparing this exam. If you have any questions, please write it in the comments section.

In this tutorial, we are going to learn about Android SQLite database CRUD example.
Android SQLite is open source relational database which can be used for performing crud operations.
You don't have to do explicit installation for it. It is available by default in android.

Let's start with simple example:

In this example, we will create a listview to show Country list and support all the CRUD operation with the help of SQLite database. When you will add a new Country to the list or delete any existing country, it will be reflected in the database.

Database Table structure:

Table Name: Country
Column
Data type
Primary key
Id
Integer
Yes
CountryName
Text
No
Population
Long
No

Source code:

Step 1 : Creating Project

Create an android application project named "SQLiteDatabaseCRUDExample".

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="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.sqlitedatabasecrudexample.MainActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Country"
        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>

You will see below screen in design view.

Step 3: Create Country class
Create a country class which will correspond to Country table in SQLite database.

package com.java2blog.sqlitedatabasecrudexample;
/*
 * This is our model class and it corresponds to Country table in database
 */

import static android.R.attr.name;

public class Country{

    int id;
    String countryName;
    long population;

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }

    // constructor
    public Country(String countryName, long population){
        this.countryName = countryName;
        this.population = population;
    }
    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;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

}

Step 4: Create SQLiteDatabaseHandler for defining database operations.

We will create a class called SQLiteDatabaseHandler which will extend SQLiteOpenHelper and override onCreate and OnUpdate method.
We will also add some CRUD methods.
  • addCountry
  • getCountry
  • getAllCountries
  • updateCountry
  • deleteCountry
  • delelteAllCountries
All above methods will interact with SQLite database and perform CRUD operations.
package com.java2blog.sqlitedatabasecrudexample;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class SQLiteDatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "countryData";

    // Country table name
    private static final String TABLE_COUNTRY= "Country";

    // Country Table Columns names
    private static final String KEY_ID = "id";
    private static final String COUNTRY_NAME = "CountryName";
    private static final String POPULATION = "Population";

    public SQLiteDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_COUNTRY + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + COUNTRY_NAME + " TEXT,"
                + COUNTRY_NAME + " LONG" + ")";
        db.execSQL(CREATE_COUNTRY_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTRY);
        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new country
    void addCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COUNTRY_NAME, country.getCountryName()); // Country Name
        values.put(POPULATION, country.getPopulation()); // Country Population

        // Inserting Row
        db.insert(TABLE_COUNTRY, null, values);
        db.close(); // Closing database connection
    }

    // Getting single country
    Country getCountry(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_COUNTRY, new String[] { KEY_ID,
                        COUNTRY_NAME, POPULATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Country country = new Country(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getLong(2));
        // return country
        return country;
    }

    // Getting All Countries
    public List<Country> getAllCountries() {
        List<Country> countryList = new ArrayList<Country>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_COUNTRY;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Country country = new Country();
                country.setId(Integer.parseInt(cursor.getString(0)));
                country.setCountryName(cursor.getString(1));
                country.setPopulation(cursor.getLong(2));
                // Adding country to list
                countryList.add(country);
            } while (cursor.moveToNext());
        }

        // return country list
        return countryList;
    }

    // Updating single country
    public int updateCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COUNTRY_NAME, country.getCountryName());
        values.put(POPULATION, country.getPopulation());

        // updating row
        return db.update(TABLE_COUNTRY, values, KEY_ID + " = ?",
                new String[] { String.valueOf(country.getId()) });
    }

    // Deleting single country
    public void deleteCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_COUNTRY, KEY_ID + " = ?",
                new String[] { String.valueOf(country.getId()) });
        db.close();
    }

    // Deleting all countries
    public void deleteAllCountries() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_COUNTRY,null,null);
        db.close();
    }

    // Getting countries Count
    public int getCountriesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_COUNTRY;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }
}

Step 5: 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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 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:layout_below="@+id/textViewId"
        android:id="@+id/textViewCountry"
        android:layout_row="1"
        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:layout_below="@+id/textViewCountry"
        android:id="@+id/textViewPopulation"
        android:layout_row="1"
        android:layout_column="2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="30dp"
        android:id="@+id/edit"
        android:text="Edit"
        android:layout_toRightOf="@+id/textViewId"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginRight="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/delete"
        android:text="Delete"
        android:layout_toRightOf="@+id/edit"
        />
</RelativeLayout>

Step 6:  Creating ArrayAdapter for ListView

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

import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {
    private Activity context;
    ArrayList<Country> countries;
    private PopupWindow pwindo;
    SQLiteDatabaseHandler db;
    BaseAdapter ba;

    public CustomCountryList(Activity context, ArrayList<Country> countries,SQLiteDatabaseHandler db) {
        this.context = context;
        this.countries=countries;
        this.db=db;
    }

    public static class ViewHolder
    {
        TextView textViewId;
        TextView textViewCountry;
        TextView textViewPopulation;
        Button editButton;
        Button deleteButton;
    }
    @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);
                        vh.textViewPopulation = (TextView) row.findViewById(R.id.textViewPopulation);
                        vh.editButton = (Button) row.findViewById(R.id.edit);
                        vh.deleteButton = (Button) row.findViewById(R.id.delete);

                // 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());
            vh.textViewPopulation.setText("" + countries.get(position).getPopulation());
            final int positionPopup = position;
            vh.editButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Log.d("Save: ", "" + positionPopup);
                    editPopup(positionPopup);

                }
            });
            vh.deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("Last Index", "" + positionPopup);
                    //     Integer index = (Integer) view.getTag();
                    db.deleteCountry(countries.get(positionPopup));

                    //      countries.remove(index.intValue());
                    countries = (ArrayList) db.getAllCountries();
                    Log.d("Country size", "" + countries.size());
                    notifyDataSetChanged();
                }
            });
        return  row;
    }

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

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

    public int getCount() {
        return countries.size();
    }

  public void editPopup(final int positionPopup)
  {
      LayoutInflater inflater = context.getLayoutInflater();
      View layout = inflater.inflate(R.layout.edit_popup,
              (ViewGroup) context.findViewById(R.id.popup_element));
      pwindo = new PopupWindow(layout, 600, 670, true);
      pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
      final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
      final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);
      countryEdit.setText(countries.get(positionPopup).getCountryName());
      populationEdit.setText("" + countries.get(positionPopup).getPopulation());
      Log.d("Name: ", "" + countries.get(positionPopup).getPopulation());
      Button save = (Button) layout.findViewById(R.id.save_popup);
      save.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              String countryStr = countryEdit.getText().toString();
              String population = populationEdit.getText().toString();
              Country country = countries.get(positionPopup);
              country.setCountryName(countryStr);
              country.setPopulation(Long.parseLong(population));
              db.updateCountry(country);
              countries = (ArrayList) db.getAllCountries();
              notifyDataSetChanged();
              for (Country country1 : countries) {
                  String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
                  // Writing Countries to log
                  Log.d("Name: ", log);
              }
              pwindo.dismiss();
          }
      });
  }
}

This class is used to populating data for ListVIew. getView method is get called for drawing each row.When you click on edit, you will see a popup to edit country Name and population. If you click on delete, country will be deleted from listview and SQLite database.

Step 7: Creating MainActivity

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

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Country> countries;
    SQLiteDatabaseHandler db;
    Button btnSubmit;
    PopupWindow pwindo;
    Activity activity;
    ListView listView;
    CustomCountryList customCountryList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity=this;
        db= new SQLiteDatabaseHandler(this);
        listView = (ListView) findViewById(android.R.id.list);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addPopUp();
                    }
                });
        Log.d("MainActivity: ", "Before reading mainactivity");
        countries = (ArrayList) db.getAllCountries();

            for (Country country : countries) {
                String log = "Id: " + country.getId() + " ,Name: " + country.getCountryName() + " ,Population: " + country.getPopulation();
                // Writing Countries to log
                Log.d("Name: ", log);
            }

                CustomCountryList customCountryList = new CustomCountryList(this, countries, db);
                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();
                    }
                });
    }

    public void addPopUp() {
        LayoutInflater inflater = activity.getLayoutInflater();
        View layout = inflater.inflate(R.layout.edit_popup,
                (ViewGroup) activity.findViewById(R.id.popup_element));
        pwindo = new PopupWindow(layout, 600, 670, true);
        pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
        final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
        final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);

        Button save = (Button) layout.findViewById(R.id.save_popup);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String countryStr = countryEdit.getText().toString();
                String population = populationEdit.getText().toString();
                Country country = new Country(countryStr, Long.parseLong(population));
                db.addCountry(country);
                if(customCountryList==null)
                {
                    customCountryList = new CustomCountryList(activity, countries, db);
                    listView.setAdapter(customCountryList);
                }
                customCountryList.countries = (ArrayList) db.getAllCountries();
                ((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
                for (Country country1 : countries) {
                    String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
                    // Writing Countries to log
                    Log.d("Name: ", log);
                }
                pwindo.dismiss();
            }
        });
    }
}

When you click on "Add Country" button, you will get a popup.You put Country name and population and Country will be added to the list.

Step 8: Running the app 

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


Click on "Add Country" button and you will get below screen. I have put Country Name as India and Population as 10000.
When you click on save, India will be saved to database. You can similarly add China, Bhutan, and Nepal. You will get below screen.

Let's edit population of china to 20000 to 30000.

When you click on save, China's population will be changed to 30000.
Let's delete Bhutan from list, click on delete corresponding to Bhutan row. When you click on delete, you will get below screen.

Callable interface represents a thread that can return a value. It is very much similar to Runnable interface except that it can return a value. Callable interface can be used to compute status or results that can be returned to invoking thread. For example: Let's say you want to perform factorial and square of some numbers, you can do it concurrently using callable interface which will return value too. Callable defines only one method as below
public interface Callable<v> {
V call() throws Exception;

}
You can define the task which you want to perform inside call method. If it executes successfully, call method will return the result else it must throw an exception. You can use ExecutorService's submit to execute Callable task. Let's see Signature of submit method in ExecutorService.
 <T> Future<T> submit(Callable<T> task);
If you notice, return type of submit method is Future.
Future is generic interface that represents value which will be returned by callable interface. As callable will return value in some future time, name seems suitable here.
There are two methods to get actual value from Future.
get() : When this method is called, thread will wait for result indefinitely.
V get(long timeout, TimeUnit unit) : When this method is called, thread will wait for result only for specified time.

Example:

This program will demonstrate use of Callable and Future. We will create one callable for calculation of square and one callable for factorial. We will submit four tasks to ExecutorService for calculation of square and factorial of 20 and 25. This program will demonstrate how can you make use of Callable and Future to execute it concurrently.
Create class called PowerCalc which implements Callable interface.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class PowerCalc implements Callable<Double>{
private double number;
 
 PowerCalc(double number)

public Double call() throws Exception {
{
  this.number=number;
 }
 
 @Override
System.out.println("Calculating Square with "+Thread.currentThread().getName());
Thread.sleep(2000);
  return Math.pow(number, number);
 }

}
Create another class called FactorialCalc which implements Callable interface.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class FactorialCalc implements Callable<Double> {
private double number; FactorialCalc(double number) {
public Double call() throws Exception {
this.number = number; } @Override System.out.println("Calculating factorial with "+Thread.currentThread().getName()); Thread.sleep(5000); double fact = 1; for (int i = 2; i <= number; i++) { fact *= i; } return fact; } }
Now create a main classed named FutureCallableMain.java.
package org.arpit.java2blog;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Executors;

public class FutureCallableMain {


ExecutorService es=Executors.newFixedThreadPool(4);
public static void main(String[] args) {
  System.out.println("Start : ");
  Future<Double> powerFuture20;

powerFuture20=es.submit(new PowerCalc(20));
Future<Double> factorialFuture20;
  Future<Double> powerFuture25;
  Future<Double> factorialFuture25;

factorialFuture25=es.submit(new FactorialCalc(25));
factorialFuture20=es.submit(new FactorialCalc(20));
  powerFuture25=es.submit(new PowerCalc(25));
   try {
System.out.println("Square of "+25+" : "+powerFuture25.get());
System.out.println("Square of "+20+" : "+powerFuture20.get());
    System.out.println("Factorial of "+20+" : "+factorialFuture20.get());

es.shutdown();
System.out.println("Factorial of "+25+" : "+factorialFuture25.get());
   } catch (InterruptedException | ExecutionException e) {
  
    e.printStackTrace();
   } 
  System.out.println("Done");
 }

}
When you run above program, you will get below output:
Start : 
Calculating Square with pool-1-thread-1
Calculating factorial with pool-1-thread-2
Calculating Square with pool-1-thread-3
Square of 20 : 1.048576E26
Calculating factorial with pool-1-thread-4
Factorial of 20 : 2.43290200817664E18
Done
Square of 25 : 8.881784197001253E34
Factorial of 25 : 1.5511210043330986E25
As you can see, we are able to execute 4 tasks concurrently which return square and Factorial of 20 and 25.

Synchronization is ability to restrict access to shared resource to only one thread. When two or more threads need access to shared resource, there has to be some mechanism such that shared resource will be used by only one thread. The process by which we can achieve it is called Synchronization.

Why do you need Synchronization?

Let's understand this with the help of example.
Let's say you want to count number of request you got for a particular URL. If you get two requests at the same time, then count may be inconsistent.

Without Synchronization:

package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 also sees count as 20 and increment it to 21. This shows that count became inconsistent.

With Synchronization:

You can achieve Synchronization using two ways.
  • synchronized method
  • synchronized block
You can not use synchronized with  instance or class variables.

synchronized method

You can make whole incrementCount() method synchronized so no two thread can access it parallelly.
package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public synchronized int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

synchronized block

You can make use block to synchronize critical section in  incrementCount() method so no two thread can access block concurrently.
package org.arpit.java2blog;

public class RequestCounter {

 private int count;

 public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

There are two types of locking in java.
  • Object level locking 
  • Class level locking

Object level locking:

Object level locking means you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance. It is used if you want to protect non static data.
You can achieve Object level locking by following.

Make method synchronized:

public synchronized int incrementCount()
{
}

Using synchronized block and lock on this:

public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }

Using synchronized block and lock on some other object:

private final Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }

Class level locking:

Class level locking means you want to synchronize static method or block so that it can be accessed by only one thread for whole class. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.
This can be achieved by following:

Make static method synchronized:

public static synchronized int incrementCount()
{
}

Using synchronized block and lock on .class:

public int incrementCount() {
  synchronized (RequestCounter.class) {
   count++;
   return count;
  }

Using synchronized block and lock on some other static object:

private final static Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }

Can two threads execute static and non static methods concurrently? 

Yes, Since two threads will acquire lock on different objects, they can be executed concurrently without any issues.

If one method of class is synchronized and other method of same class is not synchronized? Can they be executed concurrently by two threads?

Yes, because one thread will require lock to get into synchronized block but second thread which will execute non synchronized method that won't require any lock, so it can be executed concurrently.

Is it safe to call a synchronized method from another synchronized method?

Yes, it is safe to call a synchronized method from another synchronized method because when you call synchronized method, you will get lock on this object and when you call another synchronized method of same class, it is safe to execute as it already has lock on this object.
For example:
public synchronized void method1() {
  method2();
  // some code
 }
 
 public synchronized void method2() {
  // some code
 }
You are actually doing this.
public void method1() {
  synchronized (this) {
   method2();
   // some code
  }
  
 }
 
 public void method2() {
  synchronized (this) {
  // some code
  }
 }
Here if any thread calls method2 from method1, it will already have lock on this object hence It is safe to execute.

Exchanger class is introduced with java 1.5 with other classes such ConcurrentHashMap, CountDownLatch, Semaphores.
Exchanger class is used to exchange object between two threads. Exchanger simply waits until two separate threads calls exchange method, when it happens, it exchanges data supplied by threads.Two threads can pair and swap objects between them. Exchanger class may be useful in genetic algorithms or pipeline design.

It has two overloaded version of exchange method.
  • exchange(V x): It waits for another thread to arrive at exchange point and exchange object with that thread. 
  • exchange(V x, long timeout, TimeUnit unit): It waits for another thread for specific time interval provided in the method and exchange object with that thread.

Let's understand with help of example:
We have two threads i.e. Producer and Consumer and they will exchange Country objects. Producer will create Country objects and Consumer will return dummy country objects.


Let's first create Country class. It just have one attribute called countryName.
package org.arpit.java2blog;
public class Country {
  
 private String countryName; 

 public Country(String countryName) {
  super();
  this.countryName = countryName;
 }

 public String getCountryName() {
  return countryName;
 }
}
Now we will create main class called ExchangerExampleMain.java and it will have two other classes called Producer and Consumer which will implement runnable interface.
package org.arpit.java2blog;

import java.util.concurrent.Exchanger;

public class ExchangerExampleMain {

    public static void main(String[] args) {
        Exchanger<Country> exchanger = new Exchanger<Country>();
        // Starting two threads
        new Thread(new Producer(exchanger)).start();
        new Thread(new Consumer(exchanger)).start();
    }
}

class Producer implements Runnable {
   
    Exchanger<Country> ex;
    Producer(Exchanger<Country> ex){
        this.ex = ex;
       
    }
    @Override
    public void run() {
        for(int i = 0; i < 2; i ++){
          Country country=null ;
         if(i==0)
               country =new Country("India");
         else
          country =new Country("Bhutan");
         
            try {
                // exchanging with an dummy Country object
                Country dummyCountry = ex.exchange(country);
                System.out.println("Got country object from Consumer thread : "+dummyCountry.getCountryName());
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }   
    }
}

class Consumer implements Runnable {
  
    Exchanger<Country> ex;
    Consumer(Exchanger<Country> ex){
        this.ex = ex;
    }
    @Override
    public void run() {
        for(int i = 0; i < 2; i ++){
            try {
                // Getting Country object from producer thread
                // giving dummy country object in return
                Country country = ex.exchange(new Country("Dummy"));
                System.out.println("Got country object from Producer thread : "+country.getCountryName());
                
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }       
    }
}
When you run above program, you will get below output.
Got country object from Consumer thread : Dummy
Got country object from Producer thread : India
Got country object from Consumer thread : Dummy
Got country object from Producer thread : Bhutan
If you notice, producer has exchanged two country object (India and Bhutan) with consumer and got dummy country objects in return.
If you want to understand more realistic use of Exchanger. Producer and consumer may exchange buffers. When buffer is full, Producer will provide full buffer to consumer and Consumer will return empty buffer in return.

In this tutorial, we will learn about Executor's newCachedThreadPool factory method.
In the last tutorial, I have shared introduction to ThreadPoolExecutor. If you are not aware of concepts of ThreadPoolExecutor, you should go through that first.

Executor's newCachedThreadPool  factory method :

This method returns an unbounded thread pool. It sets maximum pool size to Integer.Max and it will create new threads depending on demand. If demand decreases, it will tear down threads if threads are idle for more than 1 min.
Example:
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.newCachedThreadPool factory method
  ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

  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());
   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
Fetching data from File :1 by pool-1-thread-1
Fetching data from File :2 by pool-1-thread-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 :3 by pool-1-thread-3
Fetching data from File :4 by pool-1-thread-4
A new file has been added to read : File :5
Fetching data from File :5 by pool-1-thread-5
A new file has been added to read : File :6
Fetching data from File :6 by pool-1-thread-6
A new file has been added to read : File :7
Fetching data from File :7 by pool-1-thread-7
A new file has been added to read : File :8
A new file has been added to read : File :9
Fetching data from File :8 by pool-1-thread-8
A new file has been added to read : File :10
Fetching data from File :9 by pool-1-thread-9
Fetching data from File :10 by pool-1-thread-10
If you notice, we have submitted 10 tasks and it has created 10 new threads depending on demand.If any thread remains idle for more than one minute, it will tear it down. newCachedThreadPool is a good choice when you want better queuing performance than newFixedThreadPool. If you want to restrict number of concurrent task for resource management, go with newFixedThreadPool.

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.
 

Java tutorial for beginners Copyright © 2012