ZOFTINO.COM android and web dev tutorials

Android Get Address List From Location Name Using Geocoder Example

Using Geocoder, you can get list of addresses by location or address name. For that, Geocoder provides getFromLocationName method which takes location name as parameter and returns list of addresses which match to the given location name.

In this post, I’ll show how to use getFromLocationName method of Geocoder with an example.

In your app, if you want to develop a feature that gets address by current location of the device, please see android get address by current location tutorial.

Get Addresses from Location Name Example Output

android addresses by address name using geocoder example

Get Addresses from Location Name Example

Since getFromLocationName should not be called on the main thread as it will block the thread, we’ll use intent service to call getFromLocationName method of GeoCoder. As we need to display the address list in UI, we need to create result receiver and put it in the intent to make the object available to intent service so that results can be displayed in UI.

The example allows user to enter location name. On submitting the location name, activity creates an intent passing location name and result receiver as extras and starts the service.

The service calls getFromLocationName method on GeoCoder and sends address list to results receiver which displays the address list in the list view.

Activity Layout

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AddressesByNameActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/address_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="Address List By Name"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/address_hint"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/address_label">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/addresses_t"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Address Name" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/addresses_b"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="getAddressesByName"
        android:text="Get Addresses"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/address_hint" />

    <ListView
        android:id="@+id/addresses_lst"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/addresses_b" />

</android.support.constraint.ConstraintLayout>

Activity

import android.content.Intent;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AddressesByNameActivity extends AppCompatActivity {
    
    private AddressesByNameActivity.AddressListResultReceiver addressResultReceiver;

    private TextInputEditText addressNameTv;
    private ListView addressListView;

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

        Toolbar tb = findViewById(R.id.toolbar);
        setSupportActionBar(tb);
        tb.setSubtitle("Addresses By Name");

        addressNameTv = findViewById(R.id.addresses_t);
        addressListView = findViewById(R.id.addresses_lst);

        addressResultReceiver = new AddressListResultReceiver(new Handler());

    }

    public void getAddressesByName(View view){
        getAddresses(addressNameTv.getText().toString());
    }

    private void getAddresses(String addName) {
        if (!Geocoder.isPresent()) {
            Toast.makeText(AddressesByNameActivity.this,
                    "Can't find address, ",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, AddressesByNameIntentService.class);
        intent.putExtra("address_receiver", addressResultReceiver);
        intent.putExtra("address_name", addName);
        startService(intent);
    }

    private class AddressListResultReceiver extends ResultReceiver {
        AddressListResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            if (resultCode == 0) {
                Toast.makeText(AddressesByNameActivity.this,
                        "Enter address name, " ,
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (resultCode == 1) {
                Toast.makeText(AddressesByNameActivity.this,
                        "Address not found, " ,
                        Toast.LENGTH_SHORT).show();
                return;
            }

            String[] addressList = resultData.getStringArray("addressList");
            showResults(addressList);
        }
    }

    private void showResults(String[] addressList){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, addressList);
        addressListView.setAdapter(arrayAdapter);
    }
}

Intent Service

import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

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

public class AddressesByNameIntentService extends IntentService {

    private static final String IDENTIFIER = "AddressesByNameIS";
    private ResultReceiver addressResultReceiver;

    public AddressesByNameIntentService() {
        super(IDENTIFIER);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String msg = "";
        addressResultReceiver = intent.getParcelableExtra("address_receiver");

        if (addressResultReceiver == null) {
            Log.e(IDENTIFIER,
                    "No receiver in intent");
            return;
        }

        String addressName = intent.getStringExtra("address_name");

        if (addressName == null) {
            msg = "No name found";
            sendResultsToReceiver(0, msg, null);
            return;
        }

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;

        try {
            addresses = geocoder.getFromLocationName(addressName, 5);
        } catch (Exception ioException) {
            Log.e("", "Error in getting addresses for the given name");
        }

        if (addresses == null || addresses.size()  == 0) {
            msg = "No address found for the address name";
            sendResultsToReceiver(1, msg, null);
        } else {
            Log.d(IDENTIFIER, "number of addresses received "+addresses.size());
            String[] addressList = new String[addresses.size()] ;
            int j =0;
            for(Address address : addresses){
                ArrayList<String> addressInfo = new ArrayList<>();
                for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                    addressInfo.add(address.getAddressLine(i));
                }
                addressList[j] = TextUtils.join(System.getProperty("line.separator"),
                        addressInfo);
                Log.d(IDENTIFIER,addressList[j]);
                j++;
            }
            sendResultsToReceiver(2,"", addressList);
        }
    }
    private void sendResultsToReceiver(int resultCode, String message, String[] addressList) {
        Bundle bundle = new Bundle();
        bundle.putString("msg", message);
        bundle.putStringArray("addressList", addressList);
        addressResultReceiver.send(resultCode, bundle);
    }
}

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zoftino.com.googleplayservices">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".AddressesByNameActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".AddressesByNameIntentService"
            android:exported="false"></service>
    </application>