<file_sep>


package com.example.pratik.jpa2;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.pratik.jpa2.Model.Address;
import com.example.pratik.jpa2.Model.Company;
import com.example.pratik.jpa2.Model.Contacts;
import com.example.pratik.jpa2.Model.Geo;

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

/**
 * Created by Pratik on 08-Dec-16.
 */

public class UserDatabaseHandler extends SQLiteOpenHelper {

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

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

    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_STREET = "street";
    private static final String KEY_SUITE = "suite";
    private static final String KEY_CITY = "city";
    private static final String KEY_ZIPCODE = "zipcode";
    private static final String KEY_LAT = "lat";
    private static final String KEY_LNG = "lng";
    private static final String KEY_PHONE = "phone";
    private static final String KEY_WEBSITE = "website";
    private static final String KEY_COMPANY_NAME = "companyname";
    private static final String KEY_CATCTPHRASE = "catchphrase";
    private static final String KEY_BS = "bs";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_NAME + " TEXT,"
                + KEY_USERNAME + " TEXT,"
                + KEY_EMAIL + " TEXT,"
                + KEY_STREET + " TEXT,"
                + KEY_SUITE + " TEXT,"
                + KEY_CITY + " TEXT,"
                + KEY_ZIPCODE + " TEXT,"
                + KEY_LAT + " TEXT,"
                + KEY_LNG + " TEXT,"
                + KEY_PHONE + " TEXT,"
                + KEY_WEBSITE + " TEXT,"
                + KEY_COMPANY_NAME + " TEXT,"
                + KEY_CATCTPHRASE + " TEXT,"
                + KEY_BS + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_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_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    void addContact(ArrayList<Contacts> contactses) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        for (int i = 0; i <contactses.size() ; i++) {
            values.put(KEY_ID, contactses.get(i).getId());
            values.put(KEY_NAME, contactses.get(i).getName());
            values.put(KEY_USERNAME, contactses.get(i).getUsername());
            values.put(KEY_EMAIL, contactses.get(i).getEmail());

            for (int j = 0; j <contactses.get(i).getAddresses().size() ; j++) {
                values.put(KEY_STREET, contactses.get(i).getAddresses().get(j).getStreet());
                values.put(KEY_SUITE,  contactses.get(i).getAddresses().get(j).getSuite());
                values.put(KEY_CITY,  contactses.get(i).getAddresses().get(j).getCity());
                values.put(KEY_ZIPCODE, contactses.get(i).getAddresses().get(j).getZipcode());

                for (int k = 0; k <contactses.get(i).getAddresses().get(j).getGeos().size() ; k++) {
                    values.put(KEY_LAT, contactses.get(i).getAddresses().get(j).getGeos().get(k).getLat());
                    values.put(KEY_LNG, contactses.get(i).getAddresses().get(j).getGeos().get(k).getLng());
                }
            }

            values.put(KEY_PHONE, contactses.get(i).getId());
            values.put(KEY_WEBSITE, contactses.get(i).getId());

            for (int j = 0; j <contactses.get(i).getCompanies().size() ; j++) {
                values.put(KEY_COMPANY_NAME, contactses.get(i).getCompanies().get(j).getName());
                values.put(KEY_CATCTPHRASE, contactses.get(i).getCompanies().get(j).getCatchPhrase());
                values.put(KEY_BS, contactses.get(i).getCompanies().get(j).getBs());
            }
        }

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


    public List<Contacts> getAllContacts() {
        List<Contacts> contactList = new ArrayList<Contacts>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contacts contact = new Contacts();
                contact.setId(cursor.getString(0));
                contact.setName(cursor.getString(1));
                contact.setUsername(cursor.getString(2));
                contact.setEmail(cursor.getString(3));

                Address address = new Address();
                address.setStreet(cursor.getString(4));
                address.setSuite(cursor.getString(5));
                address.setCity(cursor.getString(6));
                address.setZipcode(cursor.getString(7));


                Geo geo = new Geo();
                geo.setLat(cursor.getString(8));
                geo.setLng(cursor.getString(9));
                ArrayList<Geo> geos = new ArrayList<>();
                geos.add(geo);

                contact.setPhone(cursor.getString(10));
                contact.setWebsite(cursor.getString(11));

                Company company = new Company();
                company.setName(cursor.getString(12));
                company.setCatchPhrase(cursor.getString(13));
                company.setBs(cursor.getString(14));

                ArrayList<Address> addresses = new ArrayList<>();
                address.setGeos(geos);
                addresses.add(address);

                ArrayList<Company> companies = new ArrayList<>();
                companies.add(company);

                contact.setAddresses(addresses);
                contact.setCompanies(companies);
                contactList.add(contact);

                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }
}<file_sep>package com.example.pratik.jpa2;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.example.pratik.jpa2.Adapter.CountryAdapter;
import com.example.pratik.jpa2.DatabaseHandler.CountryDatabaseHandler;
import com.example.pratik.jpa2.Model.Worldpopulation;

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

import java.util.ArrayList;

/**
 * Created by Pratik on 08-Dec-16.
 */

public class CountryActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    CountryAdapter countryAdapter;
    private ProgressDialog pDialog;
    private ListView list_view;
    CountryDatabaseHandler countryDatabaseHandler;
    ArrayList<Worldpopulation> worldpopulationArrayList;
    ArrayList<Worldpopulation> worldpopulationArrayList1;

    // URL to get contacts JSON
    private static String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_country);

        worldpopulationArrayList = new ArrayList<Worldpopulation>();
        worldpopulationArrayList1 = new ArrayList<Worldpopulation>();
        countryDatabaseHandler = new CountryDatabaseHandler(CountryActivity.this);
        list_view = (ListView) findViewById(R.id.list_view);

        new GetContacts().execute();
    }


    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override

        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(CountryActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response

            if (isNetworkAvailable()) {
                String jsonStr = sh.makeServiceCall(url);

                Log.e(TAG, "Response from url: " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node

                        JSONArray worldpopulation1 = jsonObj.getJSONArray("worldpopulation");

                        // looping through All Contacts
                        for (int i = 0; i < worldpopulation1.length(); i++) {
                            JSONObject c = worldpopulation1.getJSONObject(i);

                            Worldpopulation worldpopulationObj = new Worldpopulation();
                            String id = c.getString("rank");
                            worldpopulationObj.setRank(id);
                            String country1 = c.getString("country");
                            worldpopulationObj.setCountry(country1);
                            String population = c.getString("population");
                            worldpopulationObj.setPopulation(population);
                            String flag = c.getString("flag");
                            worldpopulationObj.setFlag(flag);

                            worldpopulationArrayList.add(worldpopulationObj);


                        }

                        countryDatabaseHandler.addContact(worldpopulationArrayList);
                    } catch (final JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });

                    }
                } else {
                    Log.e(TAG, "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                            countryAdapter = new CountryAdapter(CountryActivity.this, worldpopulationArrayList1);
                            list_view.setAdapter(countryAdapter);
                            countryAdapter.notifyDataSetChanged();
                        }
                    });

                }
            } else {
                worldpopulationArrayList = (ArrayList<Worldpopulation>) countryDatabaseHandler.getAllContacts();
            }


            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */


            countryAdapter = new CountryAdapter(CountryActivity.this, worldpopulationArrayList);
            list_view.setAdapter(countryAdapter);
            countryAdapter.notifyDataSetChanged();
        }

    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}<file_sep>package com.example.pratik.jpa2.Adapter;

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

import com.example.pratik.jpa2.Model.Worldpopulation;
import com.example.pratik.jpa2.R;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by Pratik on 08-Dec-16.
 */

public class CountryAdapter extends BaseAdapter {
    Context context;
    List<Worldpopulation> worldpopulationList;

    public CountryAdapter(Context context, List<Worldpopulation> items) {
        this.context = context;
        this.worldpopulationList = items;
    }

    /*private view holder class*/
    private class ViewHolder {
        ImageView img_flag;
        TextView tv_country;
        TextView tv_rank;
        TextView tv_population;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.country_list_raw, null);
            holder = new ViewHolder();
            holder.tv_rank = (TextView) convertView.findViewById(R.id.tv_rank);
            holder.tv_country = (TextView) convertView.findViewById(R.id.tv_country);
            holder.tv_population = (TextView) convertView.findViewById(R.id.tv_population);


            holder.img_flag = (ImageView) convertView.findViewById(R.id.img_flag);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        Worldpopulation worldpopulation = (Worldpopulation) getItem(position);


        holder.tv_rank.setText(worldpopulation.getRank());
        holder.tv_country.setText(worldpopulation.getCountry());
        holder.tv_population.setText(worldpopulation.getPopulation());
        Picasso.with(context)
                .load(worldpopulation.getFlag())
                .placeholder(R.mipmap.ic_launcher)
                .into(holder.img_flag);


        return convertView;
    }

    @Override
    public int getCount() {
        return worldpopulationList.size();
    }

    @Override
    public Object getItem(int position) {
        return worldpopulationList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return worldpopulationList.indexOf(getItem(position));
    }
}