Share your knowledge

Saturday 11 March 2017

Android External Storage

There are several ways(Shared preferences, Internal storage, External storage, SQLite) to save data in android. Here we will discuss about Internal Storage.

Here is our final output:





Here you can download the source code: download

External storage is used to write and read data. User has a permission to access these files at anytime.

Primary External Storage: Inbuilt shared storage

Second External Storage: Removable storage (Ex: SD Card)

1. Open AndroidManifest.xml and below two permissions


    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


2. Open activity_main.xml and paste below code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.externalstorage.MainActivity">


    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fontFamily="monospace"
        android:hint="Write some data here..."
        android:paddingLeft="10dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/file_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:padding="10dp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/file_path"
        android:gravity="center">

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="save" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/save"
            android:text="read" />

    </RelativeLayout>


</RelativeLayout>



3. Open MainActivity.java and paste below code



package com.externalstorage;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private EditText data;
    private Button save, read;
    private TextView filePathTextView;

    private String fileName = "noteFile.txt";
    private String filePath = "myStore";
    private File noteFile;
    private StringBuilder dataBuilder = new StringBuilder();

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

        data = (EditText) findViewById(R.id.editText);

        save = (Button) findViewById(R.id.save);
        read = (Button) findViewById(R.id.read);

        filePathTextView = (TextView) findViewById(R.id.file_path);


        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (data.getText().toString().length()>0){
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(noteFile);

                        fileOutputStream.write(data.getText().toString().getBytes());

                        fileOutputStream.close();
                    }
                    catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }

                    filePathTextView.setText("");
                    filePathTextView.setText("noteFile.txt file saved to external storage");

                }
                else{
                    Toast.makeText(MainActivity.this,"Enter some data",Toast.LENGTH_SHORT).show();
                }


            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    FileInputStream fileInputStream = new FileInputStream(noteFile);

                    //creating instance of DataInputStream
                    DataInputStream dataInputStream = new DataInputStream(fileInputStream);

                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
                    String line;

                    while ((line=bufferedReader.readLine())!=null){
                        dataBuilder.append(line);
                    }

                    fileInputStream.close();
                }
                catch (FileNotFoundException e){
                    e.printStackTrace();
                }
                catch (IOException e){
                    e.printStackTrace();
                }

                filePathTextView.setText("");
                filePathTextView.setText("noteFile.txt data recieved from external storage");

                data.setText(dataBuilder.toString());
            }
        });


        //checking whether external storage is avialble or not
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            //external storage is not available and is not writable, so we are making save button as not clickable

            save.setEnabled(false);
        } else {

            //if external storage is avilable and is writable
            noteFile = new File(getExternalFilesDir(filePath),fileName);
        }
    }

    private static boolean isExternalStorageAvailable() {

        /**
         * Returns the current state of the primary shared/external storage media.
         *
         * @see #getExternalStorageDirectory()
         * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
         *         {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
         *         {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
         *         {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
         *         {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
         */
        String exeStoragestate = Environment.getExternalStorageState();

        if (exeStoragestate.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageReadOnly() {
        //if storage is only for read, then we can't do any write operations

        String exeStorageState = Environment.getExternalStorageState();

        if (exeStorageState.equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return true;
        }
        return false;
    }
}


Android Internal Storage Example

There are several ways(Shared preferences, Internal storage, External storage, SQLite) to save data in android. Here we will discuss about Internal Storage.

Note: Saving files to the internal storage are private to the application, and other applications will not have access to these files.

Output will look like below:



Download code from here: internal storage

1. Create a project and name it as Internal Storage

2. Open activity_main.xml and paste below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.internalstorage.MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fontFamily="monospace"
        android:hint="Enter some data here"
        android:paddingLeft="10dp"
        android:textStyle="bold" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_marginTop="20dp"
        android:gravity="center">

        <Button
            android:id="@+id/write"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="write" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/write"
            android:gravity="center"
            android:text="read" />
    </RelativeLayout>

</RelativeLayout>

3. Open MainActivity.java and paste below code



package com.internalstorage;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private EditText enteredData;
    private Button write, read;

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

        enteredData = (EditText) findViewById(R.id.editText);

        write = (Button) findViewById(R.id.write);
        read = (Button) findViewById(R.id.read);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (enteredData.getText().toString().length() > 0) {
                    writeData(enteredData.getText().toString());
                } else {
                    showMessage();
                }

            }
        });


        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enteredData.setText(readData());
            }
        });
    }

    private void showMessage() {
        Toast.makeText(MainActivity.this, "Please enter some data", Toast.LENGTH_SHORT).show();
    }

    private void writeData(String data) {

        try {
            //Using FileOutputStream we can write data to the specified file
            //openFileOutput method will take file name and mode as parameters, and return instance of fileOutputStream

            //openFileOutput method is used to create and save a file
            FileOutputStream fileOutputStream = openFileOutput("notes", MODE_PRIVATE);
            fileOutputStream.write(data.getBytes());
            fileOutputStream.close();

            Toast.makeText(MainActivity.this,"Data saved successfully",Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String readData() {

        int c;
        StringBuilder data = new StringBuilder();
        try {
            //openFileInput method is used to open and read a file
            FileInputStream fileInputStream = openFileInput("notes");
            //checking for end of file
            while ((c = fileInputStream.read()) != -1) {
                data.append(Character.toString((char) c));
            }
            fileInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data.toString();
    }
}








Android ListView

ListView: is a View which groups several items and display them in a vertical scrollable list.

Adapter: Adapter is bridge between UI component and the data which fills that UI component.

Out put will look like below:




Here is the source codelistview

1. Create Project with name ListView with Activity name as MainActivity.java.

2. Open activity_main.xml and paste below code(for listview)

<?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="com.listview.MainActivity">

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

</RelativeLayout>



2. Open strings.xml and paste below code.


    <string-array name="friends">

        <item>Friend A</item>
        <item>Friend B</item>
        <item>Friend C</item>
        <item>Friend D</item>
        <item>Friend E</item>
        <item>Friend F</item>
        <item>Friend G</item>
        <item>Friend H</item>
        <item>Friend I</item>
        <item>Friend J</item>
        <item>Friend K</item>
        <item>Friend L</item>
        <item>Friend M</item>
        <item>Friend N</item>
        <item>Friend O</item>
        <item>Friend P</item>

    </string-array>


2. create list_item inside res ->values
paste below code


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/friend_name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="10dp"
    android:text="asdf"
    android:layout_centerHorizontal="true"
    android:textSize="20dp"
    android:textAllCaps="true"
    android:textStyle="bold" >
</TextView>

3. Open MainActivity.java and paste below code


package com.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        //creating object of listview
        listView = (ListView)findViewById(R.id.listview);

        //getting string array from resourses(values->strings.xml->friends)
       final String[] friends = getResources().getStringArray(R.array.friends);

        //creating array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,friends);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //showing toast message
                Toast.makeText(getApplicationContext(),friends[position],Toast.LENGTH_LONG).show();

            }
        });
    }
}








Android Implicit and Explicit Intents

Intents: Intents are used to start components (activity, service, or broadcast receivers) or send data between one component to other component.

Here is the output:



Download source code from here: Intents example

Explicit Intent: 
1. We need to specify name of the component.
2. Explicit intents are used to start the components in the same application
3. Below is the example to start WelcomeActivity



Intent explicitIntent = new Intent(MainActivity.this, WelcomeActivity.class);
startActivity(explicitIntent);



Implicit Intent:


1. Will not specify name of the component
2. System automatically shows the applications(using data in intent filters of other applications) which can handle our task.
3. when starting implicit intent, and if there is no application which can handle your task, then app may crash, so before starting the activity, we have to check whether any application is there to handle our task using resolveActivity.





Example:1

1. suppose we want to view my blogspot("http://andytechs.blogspot.in/")
2. we need webview to load this url
3. instead of using our own webview, i will ask for the system to open any application which canhandle my task(opening that url in the webview)
4. this can be done by using Actions
5. During an implicit intent, the Android system searches for all the registered
components(through intent filters) for the specific action and data type.


If only one component is found, that is triggered but when several of them are identified a dialog ispresented to the user from which he can make a suitable selection.

Intent implicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://andytechs.blogspot.in/"));
startActivity(implicitIntent);

  
Example2:

1. let suppose we want to share(send) data in gmail, whatsapp, facebook etc...
2. specify the action(send)
3. setType is used to set the MIME type(In the previous example, we passed url and the system determines theappropriate MIME type required bye the intent.
4. But in the second example we should specify the MIME type using setType(which helps android in determiningwhich activivities should recieve the intent.
5. put extra is used to put the data which we want to share


Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,"Welcome to android learning tutorials by suresh yadam");

startActivity(shareIntent);


                


Friday 13 January 2017

Android Studio Shortcut keys - Very Important




1. Save all ( CTRL+S )
 
2. Maximize / minimize ( CTRL+SHIFT+F12 )  
 
3. Inspect current file with current profile (ALT+SHIFT+I) 
 
4. Quick switch scheme (CTRL+`
 
5. Open project structure (CTRL+ALT+SHIFT+S)



6. Search every where (Double Shift)

7. Find (CTRL+F)

8. Find next (F3)

9. Find previous (SHIFT+F3)

10. Replace (CTRL+SHIFT+R)

11. Find class (CTRL+N)

12. Find file (CTRL+SHIFT+N)

13. Find in path (CTRL+SHIFT+F)




14. Open file structure popup (CTRL+F12)

15. Navigate between open editor tabs (ALT+LEFT/RIGHT ARROWS)

16. Open Current editor tab in new window (SHIFT+F4)

17. Recently edited files (CTRL +SHIFT+E)

18. Go to last edit locatoin (CTRL+SHIFT+BACKSPACE)

19. Close active editor tab (CTRL + F4)

20. Return to editor window from tool window (ESC)

21. Go to line (CTRL+G)




22. Generate code (getters, setters, constructors etc) (ALT+INSERT)

23. Override methods (CTRL+O)

24. Collapse or expand current code block (CTRL+ PLUS/MINUS)

25. Duplicate current line or selection (CTRL+D)

26. Quick documentation lookup (CTRL+Q)

27. Show parameters for selected method (CTRL+P)

28. Go to declaration - (CTRL+CLICK)

29. Open quick definition lookup (CTRL+SHIFT+I)

30. Comment /uncomment with line comment (CTRL+/)

31. Comment /uncomment with block comment (CTRL+SHIFT+/)

32. Select successively increasing code block (CTRL+W)

33. Decrease current selection to previous state (CTRL+SHIFT+W)

34. Move to code block start (CTRL+[)

35. Move to code block end (CTRL+])

36. Select to the code block start (CTRL+SHIFT+[)

37. Select to the code block end (CTRL+SHIFT+])




38. Make project (build) - (CTRL+F9)

39. Build and run (SHIFT+F10)

40. Copy (F5)

41. Move (F6)

42. Delete (DELETE)

43. Rename (SHIFT+F6)















Tuesday 10 January 2017

Location can be determined in Android Application By Two Ways:

 Location can be determined in Android Applications by two ways:
  1. Using NETWORK_PROVIDER
  2. Using GPS_PROVIDER
Using Network Provider: The network provider determines the location of the users using cell towers, wifi points and etc. This location provider is faster in response. This is mostly used to get location inside rooms or buildings.

Permissions required to use Network Provider are either,

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

Using Gps Provider: The GPS Provider determines the location of the users using satellites. The GPS receiver in the mobile receives the signals from satellites and process to determine exact locations, but it takes more time for response and causes delay. It works better in outdoors.

Permission required to use Gps Provider is,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
 
 
 
sources from:
 
http://vastinfos.com/2016/07/difference-between-fine-and-coarse-locations-android-gps/

Getting Current Location Using Fused Location API

Let us develop an application to get the current location(last known location) address using Fused Location API Service from Google Play services.


Our Final Output looks like below:



Download code from here


Here we will use Google play services Location APIs (Fused Location Provider) to get the exact last known location(which is nothing but current location) of the device.

Set up Google Play Services: To develop an application using Google Play services APIs, you need to first set up your project with Google Services SDK.
If you haven't installed the Google Play services SDK yet, then follow below steps:

1. Click on SDK Manager icon as shown below




2. Click on Launch Standalone SDK Manager as shown in below figure.



3. Expand Extras and install Google Repository as shown below



4. Add Dependencies to make your app work with Google Play services APIs, and Click on Sync Now after adding dependency.



dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services-location:10.0.1'

}

Note: Be sure you update this version number(10.0.1) each time Google Play services is updated, while posting this blog it is 10.0.1.

You can now begin developing features with Google Play services APIs. 

Selectively compiling APIs: Before 6.5 versions of Google Play services you should compile entire package of
APIs (compile 'com.google.android.gms:play services:10.0.1')into your application. Doing so is difficult to keep the number of methods under 65,536 limit. But you can now include selective api (based on your need).

If you want to work with wearable watches then you can only include wearable related api instead of entire package.

compile 'com.google.android.gms:play-services-wearable:10.0.1'
 
Some of other Individual Google Play services APIs:

1. Google+ :  com.google.android.gms:play-services-plus:10.0.1
2. Google Account Login: com.google.android.gms:play-services-auth:10.0.1

3. Google Actions, Base Client Library:com.google.android.gms:play-services-base:10.0.1
 
4.Google Address API: com.google.android.gms:play-services-identity:10.0.1

5.Firebase App Indexing: com.google.firebase:firebase-appindexing:10.0.1

6. Google Analytics : com.google.android.gms:play-services-analytics:10.0.1

and more....

5. Specifying App Permissions:  Application that needs location services must include either Fine Location or Coarse location permission based on your need.


Note: 

1. See the differences between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.

2. Location can be determined by two ways:
  1. Using NETWORK_PROVIDER
  2. Using GPS_PROVIDER
follow this for more details.

Let's Create Android Project:


1. Create a new project in Android Studio from File => New =>New Project and fill details.


2. Open Manifest.xml and add below code



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

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

2. Open values => strings.xml and add the below string values.



<resources>

    <string name="app_name">CurrentLocation</string>
    <string name="latitude">Latitude:</string>
    <string name="longitude">Longitude:</string>

</resources>

3. Open values => colors.xml and add the below code



<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="black">#000000</color>
</resources>

4. add below code under activity_main.xml



<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.currentlocation.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/latitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/latitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/longitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/longitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/latitude"
            android:layout_centerHorizontal="true"
            android:textSize="20dp" />

    </LinearLayout>

</LinearLayout>


5. open MainActivity.java and paste below code:



package com.currentlocation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private TextView latitude, longitude;
    private final int LOCATION_REQUEST_CODE = 100;

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

        latitude = (TextView) findViewById(R.id.latitude);
        longitude = (TextView) findViewById(R.id.longitude);

        //checking runtime permissions

        if (Build.VERSION.SDK_INT > 22) {

            //check run time permssion
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                //PERMISSION IS NOT GRANTED
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);

                return;
            } else {
                buildGoogleApiClient();
            }

        } else {
            buildGoogleApiClient();
        }
    }

    private void buildGoogleApiClient() {

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this, 0, this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API) //adding location Service
                    .build();

            mGoogleApiClient.connect();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient != null)
            mGoogleApiClient.disconnect();

    }


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

        try {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);

            if (mLastLocation != null) {
                latitude.setText(String.valueOf(mLastLocation.getLatitude()));
                longitude.setText(String.valueOf(mLastLocation.getLongitude()));
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            case LOCATION_REQUEST_CODE:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    buildGoogleApiClient();

                } else {

                    if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {

                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
                    }
                }
                break;
        }
    }
}

6. If you run the project, you can see latitude and longitude as shown in the below image.



6. Follow this tutorial to get address using AsyncTask