Friday, 16 September 2016

HTTP GET and POST Requests



Screen Shot:

                                          

Download Source Code

Step 1:
Open  activity_main.xml file and copy the below code.


<?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"
    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.prasad.getpostrequestex.MainActivity">

    <Button
        android:id="@+id/getRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@color/colorPrimary"
        android:padding="8dp"
        android:text="Get Request"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="18dp" />

    <Button
        android:id="@+id/postRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/getRequest"
        android:layout_centerHorizontal="true"
        android:layout_margin="30dp"
        android:background="@color/colorPrimary"
        android:padding="8dp"
        android:text="Post Request"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="18dp" />
</RelativeLayout>

Step 2:
Create ConnectionDetector.java class to check Internet connection and copy below code.


package com.prasad.getpostrequestex.background;

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

public class ConnectionDetector {
  

 
    /**
     * Checking for all possible internet providers
     * **/
    public static  boolean isConnectingToInternet(Context _context){
        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;
    }
}

Step 3:
Create ServiceResponse.java model class to store success or failure response and copy below code.



package com.prasad.getpostrequestex.background;


public class ServiceResponse {


    private boolean isSuccessOrFail;
    private String jsonResponse;


    public void setIsSuccessOrFail(boolean isSuccessOrFail) {
        this.isSuccessOrFail = isSuccessOrFail;
    }

    public boolean isSuccessOrFail() {
        return isSuccessOrFail;
    }



    public String getJsonResponse() {
        return jsonResponse;
    }

    public void setJsonResponse(String jsonResponse) {
        this.jsonResponse = jsonResponse;
    }


    public ServiceResponse(boolean isSuccessOrFail, String jsonResponse) {
        this.isSuccessOrFail = isSuccessOrFail;
        this.jsonResponse = jsonResponse;
    }


}

Step 4:
Create WebServiceCallBack.java interface to return response to activity class and copy below code.


package com.prasad.getpostrequestex.background;

public interface WebServiceCallBack {

    void onResponseReceived(Object response);


}

Step 5:
Create WebServiceAsyncTask.java class to call background assync task and copy below code.


package com.prasad.getpostrequestex.background;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.util.HashMap;


public class WebServiceAsyncTask extends AsyncTask<Object, Void, Object> {

    private ProgressDialog pDialog;
    private Context context;
    private WebServiceCallBack webServiceListener;
    private String requestUrl;
    private HashMap<String, String> extraParams;
    private int requestType;
    private boolean showProgressBar;


    public WebServiceAsyncTask(Context context, WebServiceCallBack webServiceListener, String requestUrl, HashMap<String, String> extraParams, int requestType, boolean showProgressBar) {
        this.context = context;
        this.webServiceListener = webServiceListener;

        this.requestUrl = requestUrl;
        this.extraParams = extraParams;
        this.requestType = requestType;
        this.showProgressBar = showProgressBar;


    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (showProgressBar) {
            showProgressDialog();
        }
    }

    @Override
    protected Object doInBackground(Object[] params) {

        synchronized (this) {

            boolean networkStatus = ConnectionDetector.isConnectingToInternet(context);
            ServiceResponse serviceResponse = null;

            if (networkStatus) {
                HttpWebServiceHandler serviceHandler = new HttpWebServiceHandler();

                if (requestType == 1) {
                    serviceResponse = serviceHandler.getServiceCall(requestUrl, extraParams);
                } else if (requestType == 2) {
                    serviceResponse = serviceHandler.postServiceCall(requestUrl, extraParams);
                }

            } else {
                serviceResponse = new ServiceResponse(false, HttpWebServiceHandler.NoNetWorkErrorMSG);
            }


            return serviceResponse;
        }

    }


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

        try {

            webServiceListener.onResponseReceived(reponse);
            if (showProgressBar) {
                dismissProgressDialog();
                showProgressBar = false;
            }


        } catch (final IllegalArgumentException e) {

        } catch (final Exception e) {

        } finally {
            pDialog = null;
        }


    }


    public void showProgressDialog() {

        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);

        if (!pDialog.isShowing())
            pDialog.show();
    }

    public void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing())
            pDialog.dismiss();

    }
}

Step 6:
Create HttpWabServiceHandler.java class file to call Get and Post requests and copy below code.


package com.prasad.getpostrequestex.background;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class HttpWebServiceHandler {

    static String response = null;
    public static final String NoNetWorkErrorMSG = "No Internet Connection !!!";

    public static final String ServerErrorMSG = "Error in Connection !!!";


    private static JSONObject jsonObj;

    public HttpWebServiceHandler() {

    }

    // Get Request using HttpURLConnection  Code
    public ServiceResponse getServiceCall(String requestURL, HashMap<String, String> params) {

        InputStream inputStream = null;
        HttpURLConnection conn = null;
        ServiceResponse serviceResponse = null;
        String newRequestURL = "";

        try {

            if (params != null) {
                newRequestURL = requestURL + getQueryString(params);
            } else {
                newRequestURL = requestURL;
            }

            URL url = new URL(newRequestURL);
            Log.i("URL ", newRequestURL);

            conn = (HttpURLConnection) url.openConnection();
                 /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            conn.setRequestProperty("Accept", "application/json");
            conn.setReadTimeout(500000);
            conn.setConnectTimeout(500000);
                /* for Get request */
            conn.setRequestMethod("GET");
            int statusCode = conn.getResponseCode();

                /* 200 represents HTTP OK */
            if (statusCode == HttpsURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(conn.getInputStream());
                response = convertInputStreamToString(inputStream);
                Log.i("Response", response);
                serviceResponse = new ServiceResponse(true, response);

            } else {
                response = ServerErrorMSG;
                serviceResponse = new ServiceResponse(false, response);
            }

        } catch (Exception e) {

            e.printStackTrace();
            response = ServerErrorMSG;
            serviceResponse = new ServiceResponse(false, response);

        } finally {

            if (conn != null)
                conn.disconnect();
        }

        //  Log.i("RESPONSE", response);
        return serviceResponse; // return response

    }


    // POST Request using HttpURLConnection  Code

    public ServiceResponse postServiceCall(String requestURL, HashMap<String, String> postDataParams) {
        InputStream inputStream = null;
        URL url;
        ServiceResponse serviceResponse = null;
        HttpURLConnection conn = null;
        try {

            String postParams = getQueryString(postDataParams);
            url = new URL(requestURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(500000);
            conn.setConnectTimeout(500000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(postParams);
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(conn.getInputStream());
                response = convertInputStreamToString(inputStream);
                serviceResponse = new ServiceResponse(true, response);
                Log.i("Response", response);

            } else {

                response = ServerErrorMSG;
                serviceResponse = new ServiceResponse(false, response);
            }

        } catch (Exception e) {

            e.printStackTrace();
            response = ServerErrorMSG;
            serviceResponse = new ServiceResponse(false, response);

        } finally {

            if (conn != null)
                conn.disconnect();
        }

        return serviceResponse;

    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        String result = "";

        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

            /* Close Stream */
        if (null != inputStream) {
            inputStream.close();
        }

        return result;
    }


    private String getQueryString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }


}

Step 7:
Open MainActivity.java class file and copy below code.


package com.prasad.getpostrequestex;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.prasad.getpostrequestex.background.ServiceResponse;
import com.prasad.getpostrequestex.background.WebServiceAsyncTask;
import com.prasad.getpostrequestex.background.WebServiceCallBack;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements WebServiceCallBack {

    private Button getRequestBtn, postRequestBtn;

    private int serviceRequest = 1;
    private String url;

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

        initControls();
    }

    private void initControls() {

        getRequestBtn = (Button) findViewById(R.id.getRequest);
        postRequestBtn = (Button) findViewById(R.id.postRequest);

        getRequestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                getRequestCall();

            }
        });

        postRequestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postRequestCall();

            }
        });
    }

    private void getRequestCall() {

        serviceRequest = 1;
        url = "http://androidexample.com/media/webservice/JsonReturn.php"; //Replace with your url
        WebServiceAsyncTask loginAsyncTask = new WebServiceAsyncTask(this, this, url, null, 1, true);
        loginAsyncTask.execute();

    }

    private void postRequestCall() {

        serviceRequest = 2;
        url = ""; //Replace with your url
        // if you want pass parameters,use hash map like below
        HashMap<String, String> params = new HashMap<String, String>();
//                params.put("userName", userName);
//                params.put("password", password);

        WebServiceAsyncTask loginAsyncTask = new WebServiceAsyncTask(this, this, url, params, 2, true);
        loginAsyncTask.execute();

    }

    @Override
    public void onResponseReceived(Object response) {

        try {

            ServiceResponse serviceResponse = (ServiceResponse) response;
            String jsonResponse = serviceResponse.getJsonResponse();

            if (serviceResponse.isSuccessOrFail()) {

                //Get Request response
                if (serviceRequest == 1) {

                    //As per response parse json object

                } else if (serviceRequest == 2) {
                    //Post Request response

                    //As per response parse json object
                }


            } else {
                showAlertDialog(this, jsonResponse);
            }

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


    }

    public static void showAlertDialog(Context context, String message) {

        new AlertDialog.Builder(context)
                .setTitle(context.getResources().getString(R.string.app_name))
                .setCancelable(false)
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }
}

Step 8:
Open AndroidManifest.xml file and add the internet permissions.



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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <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>

Tuesday, 13 September 2016

Get current location coordinates using GoogleApiClient example


                We have a requirement to get current location coordinates in our app. For getting current location coordinates, basically we will use GPS or Internet Providers. But now I am using Google play services to get coordinates. Google Play services provides a new FusedLocationProvider. This provider included both Internet and GPS APIs.  Fused Location Provider automatically select best method of ascertaining the user's location: either WiFi or GPS. Its also very easy to use, but we'll need to make sure we have the Google Play Services support library and add it to our Gradle build file.

Screen Shots:



                                                
Download Source Code

Step 1:
Open activity_main.xml file and copy below code.


<?xml version="1.0" encoding="utf-8"?>
<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"
    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.prasad.currentlocationex.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Current Location"
        android:textColor="@color/colorPrimary"
        android:textSize="22dp" />

    <TextView
        android:id="@+id/lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Latutude:"
        android:textColor="#000000"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/lng"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Longitude:"
        android:textColor="#000000"
        android:textSize="18dp" />

    <Button
        android:id="@+id/getLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="Get Location" />
</LinearLayout>

Step 2:
Open build.gradle (app) file and add 'com.google.android.gms:play-services:8.4.0' library in dependencies and sync that library.


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.google.android.gms:play-services:8.4.0'
}


Step 3:
Crate "GetCurrentLocation.Java"  class file and copy the below code.


package com.liquitrac.certificategeneration.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import pub.devrel.easypermissions.EasyPermissions;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

/**
 * Created by venkataprasad.kukka on 10-08-2016.
 */
public class GetCurrentLocation implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final String TAG = "GetCurrentLocation";
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;
    public Location mLastLocation;
    public String latitude, longitude;
    private final int REQUEST_CHECK_SETTINGS = 300;
    Activity context;

    public GetCurrentLocation(Activity activity) {
        context = activity;
        buildGoogleApiClient();
        createLocationRequest();
    }

    public void connectGoogleApi() {

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    public void disConnectGoogleApi() {

        if (mGoogleApiClient != null) {
            if (mGoogleApiClient.isConnected()) {
                mGoogleApiClient.disconnect();
            }
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


    protected void createLocationRequest() {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // for enable device location
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                        builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {

                final Status status = locationSettingsResult.getStatus();
                final LocationSettingsStates LS_state = locationSettingsResult.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS);

                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.

                        break;
                }
            }
        });

    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

        getCurrentLocation();

    }

    public void getCurrentLocation() {


        if (checkPermission()) {

            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (mLastLocation == null) {

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {

                latitude = String.format("%f", mLastLocation.getLatitude());
                longitude = String.format("%f", mLastLocation.getLongitude());

                if (!TextUtils.isEmpty(latitude) || !TextUtils.isEmpty(longitude)) {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                }

            }


        } else {
            requestPermission();
        }


    }


    private boolean checkPermission() {

        int result1 = ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION);
        int result2 = ContextCompat.checkSelfPermission(context, ACCESS_COARSE_LOCATION);

        return result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;

    }

    private void requestPermission() {

        ActivityCompat.requestPermissions(context, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 100);

    }


    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {

        if (mGoogleApiClient != null) {

            if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.disconnect();
                mGoogleApiClient.connect();
            } else if (!mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }

        }

    }

}


Step 4:

Open MainActivity.Java class and copy below code.


package com.prasad.currentlocationex;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView latitudeView, longitudeView;
    private Button getLocationBtn;
    GetCurrentLocation currentLoc;
    private String latitude, longitude;

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

        initControls();
        currentLoc = new GetCurrentLocation(this);
    }

    private void initControls() {

        latitudeView = (TextView) findViewById(R.id.lat);
        longitudeView = (TextView) findViewById(R.id.lng);
        getLocationBtn = (Button) findViewById(R.id.getLocation);

        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                latitude = currentLoc.latitude;
                longitude = currentLoc.longitude;

                if (TextUtils.isEmpty(latitude) || TextUtils.isEmpty(longitude)) {
                    latitude = "0.00";
                    longitude = "0.00";
                }

                latitudeView.setText("Latitude: " + latitude);
                longitudeView.setText("Longitude: " + longitude);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentLoc.connectGoogleApi();
    }

    @Override
    protected void onStop() {
        super.onStop();
        currentLoc.disConnectGoogleApi();
    }

}

Step 5:
open AndroidManifest.xml file and add the below permissions.


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

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <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>

Spinner example using AppCompatSpinner widget

          When we have a requirement to use spinner(drop down) to show list of objects in your application. Here we will see how to use Ap...