Thursday 1 September 2016

How to share the GPS location on Whatspp in Android Studio.

Creating New Project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.   
Open => app => res => layout - activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/image"
    android:paddingBottom="64dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="64dp">

    <Button
        android:id="@+id/btnShowLocation"
        android:layout_width="match_parent"
        android:layout_height="36dp"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:background="@drawable/btn_back"
        android:text="SEND LOCATION"
        android:textColor="@color/colorPrimary" />

</RelativeLayout>


Create the Java file in project.
Open app => main => src = GPSTracker.java.

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


Create the Java file in project.
Open app => main => src = GPSLocationActivity.java.

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GPSLocationActivity extends Activity {

    Button btnShowLocation;
    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // create class object
                gps = new GPSTracker(GPSLocationActivity.this);

                // check if GPS enabled       
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder geocoder = new Geocoder(GPSLocationActivity.this, Locale.ENGLISH);

                    try {
                        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

                        if (addresses != null) {
                            Address returnedAddress = addresses.get(0);
                            StringBuilder strReturnedAddress = new StringBuilder();
                            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                            }
                            final String address = strReturnedAddress.toString();
                            String message = "Latitude: " + latitude + "\n" + "Longitude: " + longitude;

                            Intent sendIntent = new Intent();
                            sendIntent.setAction(Intent.ACTION_SEND);
                            sendIntent.putExtra(Intent.EXTRA_TEXT, address);
                            sendIntent.setType("text/plain");
                            // Do not forget to add this to open whatsApp App specifically
                            sendIntent.setPackage("com.whatsapp");
                            startActivity(sendIntent);
                            finish();
                        } else {
                            Toast.makeText(GPSLocationActivity.this, "No Address returned!", Toast.LENGTH_LONG).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Toast.makeText(GPSLocationActivity.this, "Canont get Address!", Toast.LENGTH_LONG).show();
                    }
                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });
    }
}

Add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />



 May this code help you. Thanks!!!!!!
 

Friday 12 August 2016

Automatically Read income message to verify OTP, automatically fill in edit field and Redirect Android Studio.

Creating New Project.
Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.    
Open => app => res => layout - activity_otp.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#33cc88">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtMobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Please Enter your OTP below:"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="@color/colorText"
                android:textSize="18dp" />

            <EditText
                android:id="@+id/etOtp"
                android:layout_width="146dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:ems="10"
                android:inputType="number"
                android:background="#ffffff"
                android:paddingLeft="4dp" />

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

   

Create the Java file in project.
Open app => main => src = OtpActivity.java.

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class OtpActivity extends AppCompatActivity {
    public static EditText otpEditText;
    ProgressDialog dialog;
    public static final String KEY_OTP = "";
    String URL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otp);
        //Getting the Widget Id
        Init();
      
        //Automatically reditrect the screen

         otpEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Handler h = new Handler(Looper.getMainLooper());
                h.postDelayed(new Runnable() {
                    public void run() {
                        if (otpEditText.length() > 0) {
                            otpRegister();
                        }
                    }
                }, 6000);
            }
        });
    }

    private void Init() {
        otpEditText = (EditText) findViewById(R.id.etOtp);
    }

    private void otpRegister() {
        final String mOtp = otpEditText.getText().toString();
        //SHOWING THE DIALOG
        showDialog(true);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, response, Toast.LENGTH_LONG).show();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(
KEY_OTP, "");
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(OtpActivity.this, "", "Sending.....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

   private void OpenScreen() {
        Intent i = new Intent(OtpActivity.this, ChooseActivtiy.class);
        startActivity(i);
    }
   //Here is fill the OTP verify code.
    public void setOtp(String otp) {

        try {
           //****Only fill here 4 digit number***//
            Pattern p = Pattern.compile("(\\d{4})");//. represents single character
            Matcher m = p.matcher(otp);
            if (m.find()) {
                String b = m.group(1);
                otpEditText.setText(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Create the Java file in project.

Open app => main => src = SmsReceiver .java.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import com.sell.vevsa.OtpActivity;


public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    try {
                        if (senderNum.equals("HP-VERIFY")) {
                            OtpActivity Sms = new OtpActivity();
                            Sms.setOtp(message);
                        }
                    } catch (Exception e) {
                    }
                }
            }

        } catch (Exception e) {

        }
    }
}


Add permission and receiver in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<receiver android:name=".SmsReceiver ">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

May this code help you. Thanks!!!!!!

Thursday 11 August 2016

Create Dynamic views in Andorid Studio.

Creating New Project.
Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.   
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="desktop.laptop.com.customdemo.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/linearPlus"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerInParent="true"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_marginTop="16dp"
                android:gravity="center"
                android:orientation="vertical">

                <Button
                    android:id="@+id/btPlus"
                    android:layout_width="32dp"
                    android:layout_height="36dp"
                    android:text="+"
                    android:textColor="#000000" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</android.support.constraint.ConstraintLayout>


Create Add View file in project.   

Open => app => res => layout - add_view.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    android:background="#cccccc"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="18dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtBook"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Guide(s)"
            android:textColor="#000000" />

        <EditText
            android:id="@+id/etBook"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="68dp"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:paddingLeft="8dp"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="18dp"
        android:layout_marginTop="12dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtAuthor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Author/Publisher"
            android:textColor="#000000" />

        <EditText
            android:id="@+id/etAuthor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:paddingLeft="8dp"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>


Create the Java file in project.
Open app => main => src = MainActivity.java.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<ModelBook> dataArray = new ArrayList<>();
    List<ModelBookUI> UIArray = new ArrayList<>();
    int position = 0;
    Button plusButton;
    LinearLayout plusLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        plusLinearLayout = (LinearLayout) findViewById(R.id.linearPlus);
        plusButton = (Button) findViewById(R.id.btPlus);

        plusButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                position = UIArray.size();

                UIArray.add(AddView("lay" + position, position, plusLinearLayout));
            }
        });

    }

    /**********************
     * Add new view
     **************************/
    private ModelBookUI AddView(String tag, int position, LinearLayout parent) {

        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);

        View child = inflater.inflate(R.layout.add_book, parent, false);

        EditText book = (EditText) child.findViewById(R.id.etBook);
        EditText author = (EditText) child.findViewById(R.id.etAuthor);

        LinearLayout root = (LinearLayout) child.findViewById(R.id.root);

        root.setTag(tag);

        ModelBookUI model = new ModelBookUI();

        model.book_name = book;
        model.author = author;

        parent.addView(child);

        return model;
    }
}

Create the Java file in project.
Open app => main => src = ModelBook.java.

public class ModelBook {

    public String book;
    public String author;
}


Create the Java file in project.
Open app => main => src = ModelBookUI.java.

import android.widget.EditText;

public class ModelBookUI {

    public EditText book_name;
    public EditText author;
}





Screen Shot:-


Button Click
Add View

May this code help you. Thanks!!!!!!

Tuesday 9 August 2016

Retrofit Android studio post the data on Server.

We will post the following data.
{
"token":"6536a951423727727c47ed18004e2f30z",
"book_req_category": 1,
"books": [{
    "name": "Flamingo",
    "Class": "12th",
    "medium": "English",
    "is_ncert": 1,
    "publisher_name": "NCERT",
    "type": 0
}]
}


Creating New Project.

Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Volley Library to our project.  
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'


Create the Api Client java class in project.
Open app => main => src = ApiClient.java

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Laptop on 8/9/2016.
 */
public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl("http://books.vevsa.com:7001/")
                    .client(new OkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}


Create the Response java class in project.
Open app => main => src = Response.java

import com.google.gson.annotations.SerializedName;

/**
 * Created by Laptop on 8/9/2016.
 */
public class Response {
    @SerializedName("log")
    private String log;

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    @SerializedName("flag")
    private int flag;
}


Create the Interface in project.
Open app => main => src = RetrofitInterface

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
 * Created by Laptop on 8/9/2016.
 */

public interface RetrofitInterface {
    //TODO: Please check curly bracket at end point of api name :)
    @POST("req_book_auth/raise_request")
    @Headers("Accept: application/json")
    Call<Response> getAllData(@Body RequestBody params);
}


Create the Java file in project.
Open app => main => src = MainActivity.java

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;


public class MainActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;

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

    private void getData() {
        showDialog();
        JSONObject jsonObject = getObject();
        RequestBody body = null;
        if ((jsonObject) != null) {
            Log.i("JSON_DATA", "Json" + jsonObject);
            body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                    (jsonObject).toString());
            RetrofitInterface retrofitInterface = ApiClient.getClient().create(RetrofitInterface.class);
            Call<Response> call = retrofitInterface.getAllData(body);
            call.enqueue(new Callback<Response>() {
                @Override
                public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                    closeDialog();
                    Log.i("RESPONSE", "code" + response.code());

                    try {
                        Log.i("RESPONSE", "Flag:::" + response.body().getFlag());
                        Log.i("RESPONSE", "Log:::" + response.body().getLog());
                        if (response.code() == HttpURLConnection.HTTP_OK) {
                            if (response.body().getFlag() == 143) {
                                //     Toast.makeText(getApplicationContext(),"dlkashdsh"+response.body().getLog(),Toast.LENGTH_LONG).show();
                                Log.i("RESPONSE", "Success");
                            } else {
                                Log.i("RESPONSE", "Failure");
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Call<Response> call, Throwable t) {
                    Log.i("RESPONSE", "Error" + t.getMessage());
                    closeDialog();
                }
            });
        } else {
            Log.i("RESPONSE", "Error");
            closeDialog();
        }

    }

    private void showDialog() {
        progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...");
    }

    private void closeDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private JSONObject getObject() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", "6536a951423727727c47ed18004e2f30");
            jsonObject.put("book_req_category", 1);
            JSONArray jsonArray = new JSONArray();
            JSONObject object = new JSONObject();
            object.put("name", "Flamingo");
            object.put("Class", "12th");
            object.put("medium", "English");
            object.put("is_ncert", 1);
            object.put("publisher_name", "NCERT");
            object.put("type", 0);
            jsonArray.put(object);
            jsonObject.put("books", jsonArray);
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
}



Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!

Friday 29 July 2016

Android Toolbar Example.
Toolbar is a complete replacement to Android ActionBar.ToolBar works well with apps targeted to API 21 and above and it is introduced after lollipop release.

Toolbar may contain a combination of the following optional elements:
  • Using the Navigation button.
  • Using the logo Image.
  • Using the title and subtitle.
Implementing the Navigation button and icon on Toolbar.

Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.    
Open => app => res => layout - activity_main.xml.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="laptop.example.com.toolbaricon.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="58dp"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize"></android.support.v7.widget.Toolbar>
</RelativeLayout>

Create Xml file in project.
Open => app => res => menu => main.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:title="Search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
    <item
        android:id="@+id/action_setting"
        android:icon="@drawable/setting"
        android:orderInCategory="300"
        android:title="Setting"
        app:showAsAction="ifRoom"></item>
</menu>


Create the Java file in project.
Open app => main => src = MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;

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

    }

    private void ToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.drawable.hamburger);
        toolbar.setNavigationOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "Click App Logo", Toast.LENGTH_SHORT).show();
                    }
                }

        );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        switch (item.getItemId()) {
            case R.id.action_search:
                Toast.makeText(MainActivity.this, "I am Search", Toast.LENGTH_LONG).show();
                break;
            case R.id.action_setting:
                Toast.makeText(MainActivity.this, "I am Setting", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}



Output:-

 


May this code help you. Thanks!!!!!!
 

Thursday 28 July 2016

How to debug an Android app without using USB in android studio.

Open the terminal(android studio) or cmd.
  • First time  need data cable
  • Go to ADB location inside platform tools.
  • Attach data cable .
  • cmd>  adb devices(press enter)
  • adb tcpip 5555 +enter.
  • Remove cable.
  • Go to phone settings => About Phone => Status => Check IP Address.
  • adb connect IP address:5555

Example: 
  • C:\Users\Laptop>d:
  • D:\>cd AnddroidStudio\platform-tools
  • D:\AnddroidStudio\platform-tools>adb devices
  • List of devices attached
  • 0123456789ABCDEF        device
  • D:\AnddroidStudio\platform-tools>adb tcpip 5555
  • restarting in TCP mode port: 5555
  • D:\AnddroidStudio\platform-tools>adb connect 192.168.1.8:5555

After that connectivity is done(Android phone and Android studio).


May this lines help you. Thanks!!!!!!

Wednesday 27 July 2016

Spinner Example to Load JSON using Volley in android studio

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Volley Library to our project.
 compile 'com.android.support:design:22.2.0'
 compile 'com.mcxiaoke.volley:library-aar:1.0.0'


Create Xml file in project.  
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:paddingLeft="24dp"
        android:paddingRight="24dp"
        android:paddingTop="56dp">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>



Create the Config.java file in project.


package laptop.example.com.testdemo;

/**
 * Created by Laptop on 27-07-2016.
 */
public class Config {
    public static String URL = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";

    public static final String TAG_RANK = "rank";
    public static final String TAG_COUNTRY = "country";
    public static final String TAG_POPULATION = "population";
    //JSON array name
    public static final String JSON_ARRAY = "worldpopulation";
}



Create the Java file in project.
Open app => main => src = MainActivity.java



package laptop.example.com.testdemo;

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.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    ProgressDialog dialog;
    //ArrayList for Spinner Items
    private ArrayList<String> country;
    //JSON Array
    private JSONArray worldpopulation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        Login();
        Listener();

        //Initializing the ArrayList
        country = new ArrayList<String>();
    }

    private void Listener() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void Login() {

        showDialog(true);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        JSONObject json = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            json = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            worldpopulation = json.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getRank(worldpopulation);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                // map.put(KEY_EMAIl,email);

                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void getRank(JSONArray worldpopulation) {
        for (int i = 0; i < worldpopulation.length(); i++) {
            try {
                JSONObject jsonObject = worldpopulation.getJSONObject(i);
                //Adding the name of the Rank to array list
                country.add(jsonObject.getString(Config.TAG_COUNTRY));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Setting adapter to show the items in the spinner
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, country));
    }

    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(MainActivity.this, "", "Loading....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    private void Init() {
        spinner = (Spinner) findViewById(R.id.spinner);
    }

}


Add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>

May this code help you. Thanks!!!!!!

Monday 25 July 2016

How to get the data through Parsing with SQLite in android studio.

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Volley Library to our project.
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.code.gson:gson:2.2.3'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile files('libs/picasso-2.5.0.jar')  


Create Xml file in project.   

Open => app => res => layout - activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


Open => app => res => layout - row_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#307fc1"
    android:orientation="vertical"
    android:padding="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txtname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Kamal Sharma"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ffffff" />

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginLeft="42dp"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

    <TextView
        android:id="@+id/txtdes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="William Bradley 'Brad'"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtdob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="14-09-1989"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtcountry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="United States"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtheight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="1.80m"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtchildren"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="ABC,XYZ"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
  
</LinearLayout>


Create the Java file in project.

Open app => main => src = MainActivity.java

package com.appified.jsonparsingexample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity{
    ListView listView;
    CustomAdapter adapter;
    ArrayList<CustomItem> arrayList;
    DBHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listview);
        handler = new DBHandler(this);
        NetworkUtils utils = new NetworkUtils(MainActivity.this);
        if(handler.getItemCount() == 0 && utils.isConnectingToInternet())
        {
            new DataFetcherTask().execute();
        }
        else
        {
             ArrayList<CustomItem> cityList = handler.getAllItem();
            adapter = new CustomAdapter(MainActivity.this,cityList);
            listView.setAdapter(adapter);
        }
        }
    @SuppressLint("NewApi") class DataFetcherTask extends AsyncTask<Void,Void,Void> {

        @SuppressLint("NewApi") @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressWarnings("deprecation")
        @Override
        protected Void doInBackground(Void... params) {
            String serverData = null;// String object to store fetched data from server
            // HTTP Request Code start
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                serverData = EntityUtils.toString(httpEntity);
                Log.d("response", serverData);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
             // HTTP Request Code end
            // JSON Parsing Code Start
            try {
                arrayList = new ArrayList<CustomItem>();
                JSONObject jsonObject = new JSONObject(serverData);
                JSONArray jsonArray = jsonObject.getJSONArray("actors");
                for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject jsonObjectItem = jsonArray.getJSONObject(i);
                    String Name = jsonObjectItem.getString("name");
                    String Desc = jsonObjectItem.getString("description");
                    String DOB = jsonObjectItem.getString("dob");
                    String Country= jsonObjectItem.getString("country");
                    String Height = jsonObjectItem.getString("height");
                    String children=jsonObjectItem.getString("children");
                    CustomItem value = new CustomItem();
                    value.setName(Name);
                    value.setDesc(Desc);
                    value.setDob(DOB);
                    value.setCountry(Country);
                    value.setHeight(Height);
                    value.setchildren(children);
                    handler.addItem(value);  // Inserting into DB
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Json Parsing code end
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ArrayList<CustomItem> itemList = handler.getAllItem();
            adapter = new CustomAdapter(MainActivity.this,itemList);
            listView.setAdapter(adapter);
        }
    }
}

 Create the CustomListener class in project

package com.appified.jsonparsingexample;

import java.util.ArrayList;

public interface CustomListener {

    public void addItem(CustomItem city);
    public ArrayList<CustomItem> getAllItem();
    public int getItemCount();
}


 Create the CustomItem class in project

package com.appified.jsonparsingexample;


public class CustomItem {

    private int id;
    private String name;
    private String Desc;
    private String DOB;
    private String Country;
    private String height;
    private String children;
    private String Image;

    public CustomItem() {
    }

    public CustomItem(String name, String Desc, String DOB, String Country, String height, String children, String Image) {
        this.name = name;
        this.Desc = Desc;
        this.DOB = DOB;
        this.Country = Country;
        this.height = height;
        this.children = children;
        this.Image = Image;
    }

    public CustomItem(int id, String name, String Desc, String DOB, String Country, String height, String children, String Image) {
        this.id = id;
        this.name = name;
        this.Desc = Desc;
        this.DOB = DOB;
        this.Country = Country;
        this.height = height;
        this.children = children;
        this.Image = Image;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return Desc;
    }

    public void setDesc(String Desc) {
        this.Desc = Desc;
    }

    public String getDob() {
        return DOB;
    }

    public void setDob(String DOB) {
        this.DOB = DOB;
    }

    public String getCountry() {
        return Country;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getChildren() {
        return children;
    }

    public void setchildren(String children) {
        this.children = children;
    }

    public String getImage() {
        return children;
    }

    public void setImage(String Image) {
        this.Image = Image;
    }
}


Create the CustomAdapter class in project

package com.appified.jsonparsingexample;

import java.util.ArrayList;
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;


public class CustomAdapter extends BaseAdapter {

    Context context;
    ArrayList<CustomItem> listData;


    public CustomAdapter(Context context, ArrayList<CustomItem> listData) {
        this.context = context;
        this.listData = listData;
    }

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

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

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

    class ViewHolder {
        private TextView textViewCityName, txtDesc, txtDob, txtcountry, txtheight, txtchildren;
        ImageView image;

    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.row_item, null);
            viewHolder = new ViewHolder();
            viewHolder.textViewCityName = (TextView) view.findViewById(R.id.txtname);
            viewHolder.txtDesc = (TextView) view.findViewById(R.id.txtdes);
            viewHolder.txtDob = (TextView) view.findViewById(R.id.txtdob);
            viewHolder.txtcountry = (TextView) view.findViewById(R.id.txtcountry);
            viewHolder.txtheight = (TextView) view.findViewById(R.id.txtheight);
            viewHolder.image = (ImageView) view.findViewById(R.id.image);
            viewHolder.txtchildren = (TextView) view.findViewById(R.id.txtchildren);

            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.textViewCityName.setText(listData.get(position).getName());
        viewHolder.txtDesc.setText(listData.get(position).getDesc());
        viewHolder.txtDob.setText(listData.get(position).getDob());
        viewHolder.txtcountry.setText(listData.get(position).getCountry());
        viewHolder.txtheight.setText(listData.get(position).getHeight());
        viewHolder.txtchildren.setText(listData.get(position).getChildren());
        // Picasso.with(context).load(listData.get(position).getImage()).resize(150, 150).into(viewHolder.image);
      
     /*   viewHolder.image.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
          
              
            }
        });*/

        return view;
    }
}


Create the NetworkUtils class in project

package com.appified.jsonparsingexample;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetworkUtils {

    private Context context;

    public NetworkUtils(Context context) {
        this.context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}


Create the DBHandler class in project


package com.appified.jsonparsingexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;

public class DBHandler extends SQLiteOpenHelper implements CustomListener {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Database.db";
    private static final String TABLE_NAME = "item_table";
    private static final String KEY_ID = "_id";
    private static final String KEY_NAME = "_name";
    private static final String KEY_DESC = "_state";
    private static final String KEY_DOB = "_description";
    private static final String KEY_COUNTRY = "_country";
    private static final String KEY_HEIGHT = "_height";
    private static final String KEY_CHILDREN = "_children";

    String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+KEY_DESC+" TEXT,"+KEY_DOB+" TEXT,"+KEY_COUNTRY+" TEXT,"+KEY_HEIGHT+" TEXT,"+KEY_CHILDREN+" TEXT)";
    String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;

    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    @Override
    public void addItem(CustomItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try{
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, item.getName());
            values.put(KEY_DESC, item.getDesc());
            values.put(KEY_DOB,item.getDob());
            values.put(KEY_COUNTRY, item.getCountry());
            values.put(KEY_HEIGHT, item.getHeight());
            values.put(KEY_CHILDREN, item.getChildren());
            db.insert(TABLE_NAME, null, values);
            db.close();
        }catch (Exception e){
            Log.e("problem",e+"");
        }
    }

    @Override
    public ArrayList<CustomItem> getAllItem() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<CustomItem> itemList = null;
        try{
            itemList = new ArrayList<CustomItem>();
            String QUERY = "SELECT * FROM "+TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            if(!cursor.isLast())
            {
                while (cursor.moveToNext())
                {
                    CustomItem item = new CustomItem();
                    item.setId(cursor.getInt(0));
                    item.setName(cursor.getString(1));
                    item.setDesc(cursor.getString(2));
                    item.setDob(cursor.getString(3));
                    item.setCountry(cursor.getString(4));
                    item.setHeight(cursor.getString(5));
                    item.setchildren(cursor.getString(6));
                    itemList.add(item);
                }
            }
            db.close();
        }catch (Exception e){
            Log.e("error",e+"");
        }
        return itemList;
    }

    @Override
    public int getItemCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try{
            String QUERY = "SELECT * FROM "+TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        }catch (Exception e){
            Log.e("error",e+"");
        }
        return 0;
    }
}


Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!