Abstract class to get a address from current location in Android

A
public abstract class ReverseGeocoderTask extends AsyncTask<Void, Void, String> {
    private static final String TAG = "ReverseGeocoder";
    private String value = "Checking your location...";

    public abstract void onAddressFound(String address);

    private float mLat;
    private float mLng;
    private Activity mContext;

    public ReverseGeocoderTask(Activity context, Location location) {
        mContext = context;
        mLat = (float) location.getLatitude();
        mLng = (float) location.getLongitude();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        value = "Searching for address...";
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            List<Address> addressList =
                    getFromLocation(mLat, mLng, 1);
            StringBuilder sb = new StringBuilder();
            for (Address addr : addressList) {
                int index = addr.getMaxAddressLineIndex();
                sb.append(addr.getAddressLine(index));
            }

            value = sb.toString();
//          Logger.logger("Address Address    " + value);
        } catch (Exception ex) {

            Utilities.showToast(mContext,"Oops! There was an error.Please try to search your location again.");
            value = "Type your location here...";
//            Log.e(TAG, "Geocoder exception: ", ex);
        }
        return value;
    }

    @Override
    protected void onPostExecute(String location) {
        onAddressFound(value);
    }

    public static List<Address> getFromLocation(double lat, double lng, int maxResult) {

        List<Address> retList = null;
        String address = String.format(Locale.getDefault(), "https://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&language=" + Locale.getDefault(), lat, lng);
        URL myurl;
        try {
            myurl = new URL(address);
//            Logger.logger("myurl.......URl...=  ", myurl.toString());
            HttpURLConnection urlConnection = (HttpURLConnection) myurl.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);
            urlConnection.connect();
            InputStream is = urlConnection.getInputStream();
            if (is != null) {
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader responseReader = new BufferedReader(new InputStreamReader(is));
                    String responseLine;
                    StringBuilder stringBuilder = new StringBuilder();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is));
                    while ((responseLine = responseReader.readLine()) != null) {
                        stringBuilder.append(responseLine);

                    }
                    reader.close();
//                    Logger.logger("stringBuilder.......stringBuilder...=  ", stringBuilder.toString());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject = new JSONObject(stringBuilder.toString());


                    retList = new ArrayList<>();

                    Address addr = new Address(Locale.getDefault());
                    if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
                        JSONArray results = jsonObject.getJSONArray("results");
//                for (int i = 0; i < results.length(); i++) {
                        JSONObject result = results.getJSONObject(0);

                        String indiStr = result.getString("formatted_address");
//                        Logger.logger("indiStr   " + indiStr);

                        addr.setAddressLine(0, indiStr);

                        retList.add(addr);
//                }
//                        Logger.logger("retList   " + retList);
                    } else {
//                        throw new IllegalStateException("Method failed: " + response.getStatusLine());
                    }
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return retList;
    }

}

About the author

rohit.gujar
By rohit.gujar

Category