Example usage for android.location Geocoder Geocoder

List of usage examples for android.location Geocoder Geocoder

Introduction

In this page you can find the example usage for android.location Geocoder Geocoder.

Prototype

public Geocoder(Context context, Locale locale) 

Source Link

Document

Constructs a Geocoder whose responses will be localized for the given Locale.

Usage

From source file:com.cmput301w17t07.moody.CreateMoodActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_mood);
    UserController userController = new UserController();
    userName = userController.readUsername(CreateMoodActivity.this).toString();
    setUpMenuBar(this);
    location = null;// ww  w. j  av  a2 s  . co m
    date = new Date();
    Intent intent = getIntent();
    locationText = (TextView) findViewById(R.id.locationText);
    Description = (EditText) findViewById(R.id.Description);
    mImageView = (ImageView) findViewById(R.id.editImageView);

    //try to get picklocation, if it is equal to 1 that means, user just back from map not
    //other activities
    try {
        pickLocation = (int) intent.getExtras().getInt("pickLocation");
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (pickLocation == 1) {
        tempMood = (Mood) intent.getSerializableExtra("editMood");
        bitmap = (Bitmap) intent.getParcelableExtra("bitmapback");
        latitude = tempMood.getLatitude();
        longitude = tempMood.getLongitude();
        address = tempMood.getDisplayLocation();
        locationText.setText(address);
        Description.setText(tempMood.getMoodMessage());
        mImageView.setImageBitmap(bitmap);
        date = tempMood.getDate();
        displayAttributes();
    }

    /**
     * Spinner dropdown logic taken from http://stackoverflow.com/questions/13377361/how-to-create-a-drop-down-list <br>
     * Author: Nicolas Tyler, 2013/07/15 8:47 <br>
     * taken by Xin Huang 2017/03/10 <br>
     */
    //Spinner for emotion and socialsituatuion
    if (pickLocation == 0) {
        Spinner dropdown = (Spinner) findViewById(R.id.Emotion);

        String[] items = new String[] { "anger", "confusion", "disgust", "fear", "happiness", "sadness",
                "shame", "surprise" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                EmotionText = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(CreateMoodActivity.this, "Please pick a feeling!", Toast.LENGTH_SHORT).show();
            }
        });

        Spinner dropdown_SocialSituation = (Spinner) findViewById(R.id.SocialSituation);
        String[] item_SocialSituation = new String[] { "", "alone", "with one other person", "with two people",
                "with several people", "with a crowd" };
        ArrayAdapter<String> adapter_SocialSituation = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, item_SocialSituation);
        dropdown_SocialSituation.setAdapter(adapter_SocialSituation);

        dropdown_SocialSituation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                SocialSituation = parent.getItemAtPosition(position).toString();
                TextView sizeView = (TextView) findViewById(R.id.SocialText);
                sizeView.setText("  " + SocialSituation);
            }

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

    ImageButton chooseButton = (ImageButton) findViewById(R.id.Camera);

    ImageButton locationButton = (ImageButton) findViewById(R.id.location);

    ImageButton PickerButton = (ImageButton) findViewById(R.id.Picker);

    //click on PickerButton, call the datetimePicker
    PickerButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            innit();
            TimeDialog.show();
        }
    });

    chooseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, 1);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
                startActivity(intent);
            }
        }
    });

    chooseButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            try {
                Intent intent = new Intent("android.intent.action.PICK");
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
                startActivity(intent);
            }
            return true;
        }
    });

    locationButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            //check available tools
            List<String> locationList = locationManager.getProviders(true);
            if (locationList.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (locationList.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                Toast.makeText(getApplicationContext(), "Please check application permissions",
                        Toast.LENGTH_LONG).show();
            }

            //check the permission
            if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getApplicationContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                Toast.makeText(getApplicationContext(), "Get location failed, Please check the Permission",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            location = locationManager.getLastKnownLocation(provider);
            if (location == null) {
                latitude = 0;
                longitude = 0;
            } else {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

            Geocoder gcd = new Geocoder(CreateMoodActivity.this, Locale.getDefault());
            try {
                List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
                if (addresses.size() > 0)
                    address = "  " + addresses.get(0).getFeatureName() + " "
                            + addresses.get(0).getThoroughfare() + ", " + addresses.get(0).getLocality() + ", "
                            + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryCode();
                locationText.setText(address);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    //pass users' changes to map, will be passed back
    locationButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            int fromCreate = 123;
            moodMessage_text = Description.getText().toString();
            tempMood = new Mood(EmotionText, userName, moodMessage_text, latitude, longitude, null,
                    SocialSituation, date, address);
            Intent editLocation = new Intent(CreateMoodActivity.this, EditLocation.class);
            editLocation.putExtra("EditMood", tempMood);
            editLocation.putExtra("fromCreate", fromCreate);
            editLocation.putExtra("bitmap", compress(bitmap));
            startActivity(editLocation);
            return true;
        }
    });

    Button submitButton = (Button) findViewById(R.id.button5);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            moodMessage_text = Description.getText().toString();
            MoodController moodController = new MoodController();

            // --------------------------- achievements -------------------------------------
            AchievementManager.initManager(CreateMoodActivity.this);
            AchievementController achievementController = new AchievementController();
            achievements = achievementController.getAchievements();
            achievements.moodCount += 1;
            achievementController.incrementMoodCounter(EmotionText);
            achievementController.saveAchievements();
            // ------------------------------------------------------------------------------
            if (location != null || pickLocation == 1) {
                //todo can remove these if/else statements that toast message too long. They could
                // be handled in the controller
                if (!MoodController.createMood(EmotionText, userName, moodMessage_text, latitude, longitude,
                        bitmap, SocialSituation, date, address, CreateMoodActivity.this)) {
                    Toast.makeText(CreateMoodActivity.this,
                            "Mood message length is too long. Please try again.", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(CreateMoodActivity.this, TimelineActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else {
                if (!MoodController.createMood(EmotionText, userName, moodMessage_text, 0, 0, bitmap,
                        SocialSituation, date, address, CreateMoodActivity.this)) {
                    Toast.makeText(CreateMoodActivity.this,
                            "Mood message length is too long. Please try again.", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(CreateMoodActivity.this, TimelineActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }
    });
}

From source file:com.pk.ubulance.Activity.DisplayDriverActivity.java

public String getLocationName(Context mContext, Double latitude, Double longitude) {
    Geocoder myLocation = new Geocoder(mContext, Locale.getDefault());
    List<Address> myList = null;
    try {/* w  ww.  j a  v  a 2 s. c o  m*/
        myList = myLocation.getFromLocation(latitude, longitude, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Address address = (Address) myList.get(0);
    String addressStr = "";
    addressStr += address.getAddressLine(0) + ", ";
    addressStr += address.getAddressLine(1) + ", ";
    addressStr += address.getAddressLine(2);
    Log.d("Ubulance", "Your Location: " + addressStr);
    return addressStr;
}

From source file:ca.cs.ualberta.localpost.view.MapsView.java

/**
 * Function that creates a list of addresses based on search query location 
 * @return a list of i addresses/*from   ww w.j  a  v  a2  s. c  o  m*/
 */
private List<Address> addresses(int numberOfAddresses) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, numberOfAddresses);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return addresses;
}

From source file:com.yayandroid.utility.MapHelperFragment.java

/**
 * After getting myLocation, this method tries to get user's current
 * address. First with GeoCoder, if it cannot then it looks up googleApis to
 * get address online and parseS it.//from   w  ww . j  a va2 s .c  o m
 */
private void GetLocationInfo() {
    if (runningThreadGetLocationInfo || myLocation == null)
        return;

    new Thread(new Runnable() {

        @SuppressLint("NewApi")
        @Override
        public void run() {
            runningThreadGetLocationInfo = true;

            Address address = null;

            if (Build.VERSION_CODES.FROYO < Build.VERSION.SDK_INT) {
                if (Geocoder.isPresent()) {
                    try {
                        if (getActivity() != null) {
                            Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
                            List<Address> addresses = geocoder.getFromLocation(myLocation.getLatitude(),
                                    myLocation.getLongitude(), 1);
                            if (addresses.size() > 0) {
                                address = addresses.get(0);
                            }
                        }
                    } catch (Exception ignored) {
                        /*
                         * After a while, GeoCoder start to throw
                         * "Service not available" exception. really weird
                         * since it was working before (same device, same
                         * Android version etc..)
                         */
                    }
                }
            }

            if (address != null) {
                // i.e., GeoCoder success
                parseAddressInformation(address);
            } else {
                // i.e., GeoCoder failed
                fetchInformationUsingGoogleMap();
            }

            runningThreadGetLocationInfo = false;
        }

    }).start();
}

From source file:com.jackpan.TaiwanpetadoptionApp.HeadpageActivity.java

@Override
public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;/*ww w. j a va2  s . c om*/
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        Geocoder gc = new Geocoder(HeadpageActivity.this, Locale.TRADITIONAL_CHINESE);
        List<Address> lstAddress = null;
        try {
            lstAddress = gc.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
            String returnAddress = lstAddress.get(0).getAddressLine(0);
            Log.d(TAG, returnAddress);
            MyGAManager.setGaEvent(HeadpageActivity.this, "Location", "Location_now", returnAddress);
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        Log.d(TAG, "NO Location");
    }
}

From source file:com.parking.billing.ParkingPayment.java

/** Called when the activity is first created. */
@Override//from   w w w . ja v a 2s  .  com
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.parkingpayment);

    mHandler = new Handler();
    mParkingPurchaseObserver = new ParkingPurchaseObserver(mHandler);
    mBillingService = new BillingService();
    mBillingService.setContext(this);

    mPurchaseDatabase = new PurchaseDatabase(DashboardActivity.myContext);

    //Get on the spot selected 
    Intent starterIntent = getIntent();
    Bundle bundle = starterIntent.getExtras();

    TextView textAll = (TextView) findViewById(R.id.parkingAllDetailsTextView);

    /** Obtain time object **/
    String timeObj = bundle.getString("time");
    try {
        paidTime = Integer.parseInt(timeObj);
        Log.v(TAG, "Calculated time : " + paidTime);
    } catch (NumberFormatException nfe) {
        Log.v(TAG, "NumberFormatException: " + nfe.getMessage());
    }

    /** Create parkingLocationObj */
    String all = bundle.getString("info");
    parkingLocationObj = LocationUtility.convertStringToObject(all);

    /** Use the object to populate fields */
    String locAddress = "Address unavailable";
    Geocoder geoCoder = new Geocoder(DashboardActivity.myContext, Locale.getDefault());
    GeoPoint gp = new GeoPoint((int) (parkingLocationObj.getLatitude() * 1E6),
            (int) (parkingLocationObj.getLongitude() * 1E6));
    locAddress = LocationUtility.ConvertPointToLocation(gp, geoCoder);
    Log.v(TAG, "Setting address to: " + locAddress);
    parkingLocationObj.setAddress(locAddress);

    String typeToDisplay = parkingLocationObj.getType() == null ? "Not known"
            : "" + parkingLocationObj.getType();

    textAll.setText("\n" + "Address: " + parkingLocationObj.getAddress() + "\n" + "Type:" + typeToDisplay + "\n"
            + "MeterId: " + parkingLocationObj.getMeterID() + "\n"
            + "Number of Parking Spots at this location: " + parkingLocationObj.getQuantity() + "\n");

    setupWidgets();

    // Check if billing is supported.
    ResponseHandler.register(mParkingPurchaseObserver);
    if (!mBillingService.checkBillingSupported()) {
        showDialog(DIALOG_CANNOT_CONNECT_ID);
    }
}

From source file:edu.ttu.spm.cheapride.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Retrieve location and camera position from saved instance state.
    if (savedInstanceState != null) {
        mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }//from  ww w .j av a  2s .c  o  m

    // Retrieve the content view that renders the map.
    setContentView(R.layout.activity_main);

    // Build the Play services client for use by the Fused Location Provider and the Places API.
    // Use the addApi() method to request the Google Places API and the Fused Location Provider.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this).addApi(LocationServices.API).addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API).build();
    mGoogleApiClient.connect();

    //        autocompleteFragment = (PlaceAutocompleteFragment)
    //                getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    loginTextView = (TextView) findViewById(R.id.login);
    registerTextView = (TextView) findViewById(R.id.register);
    loginSeparatorTextView = (TextView) findViewById(R.id.login_separator);
    welcomeTextView = (TextView) findViewById(R.id.welcome_message);
    history = (TextView) findViewById(R.id.history);
    comparisonChart = findViewById(R.id.comparison_chart);
    rideBooking = findViewById(R.id.ride_booking);
    rideBooking.setVisibility(View.INVISIBLE);
    driveInfoBoard = findViewById(R.id.driverInfoBoard);
    bookingButtons = findViewById(R.id.bookingButtons);
    bookingButtons.setVisibility(View.INVISIBLE);
    vehicleImage = (ImageView) findViewById(R.id.vehicleImg);
    vehicleColor = (TextView) findViewById(R.id.vehicleColor);
    vehiclePlateLicense = (TextView) findViewById(R.id.vehiclePlateLicense);
    vehicleInfo = (TextView) findViewById(R.id.vehicleInfo);
    driverImage = (ImageView) findViewById(R.id.driverImg);
    driverName = (TextView) findViewById(R.id.driverName);
    driverInfo = (TextView) findViewById(R.id.driverInfo);

    uberArrivalTime = (TextView) findViewById(R.id.uber_arrival);
    lyftArrivalTime = (TextView) findViewById(R.id.lyft_arrival);
    uberCost = (TextView) findViewById(R.id.uber_cost);
    lyftCost = (TextView) findViewById(R.id.lyft_cost);
    textView_seekBar = (EditText) findViewById(R.id.textView_seekBar);

    carTypeSelection = (Spinner) findViewById(R.id.carType);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_item, CAR_TYPES);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    carTypeSelection.setAdapter(adapter);
    carTypeSelection.setOnItemSelectedListener(this);

    bookingHandler = new BookingHandler(this);

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
    ImageLoader.getInstance().init(config);
    imageLoader = ImageLoader.getInstance();

    geocoder = new Geocoder(this, Locale.getDefault());

    main = this;

    setDefaultDate();

    showDialogOnTextViewClick();

}

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {//from   w  w  w .j  a v  a 2  s  .  c  o m

        if (WeatherData.updating)
            return;

        // Prevent weather updating more frequently than every 5 mins
        if (WeatherData.timeStamp != 0 && WeatherData.received) {
            long currentTime = System.currentTimeMillis();
            long diff = currentTime - WeatherData.timeStamp;

            if (diff < 5 * 60 * 1000) {
                if (Preferences.logging)
                    Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago");

                //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context);

                return;
            }
        }

        WeatherData.updating = true;

        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        List<Address> addresses;
        if (Preferences.weatherGeolocation && LocationData.received) {
            Geocoder geocoder;
            String locality = "";
            String PostalCode = "";
            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1);

                for (Address address : addresses) {
                    if (!address.getPostalCode().equalsIgnoreCase("")) {
                        PostalCode = address.getPostalCode();
                        locality = address.getLocality();
                        if (locality.equals("")) {
                            locality = PostalCode;
                        } else {
                            PostalCode = locality + ", " + PostalCode;
                        }

                    }
                }
            } catch (IOException e) {
                if (Preferences.logging)
                    Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e);
            }

            if (PostalCode.equals("")) {
                PostalCode = Preferences.weatherCity;
            }
            if (locality.equals("")) {
                WeatherData.locationName = PostalCode;
            } else {
                WeatherData.locationName = locality;
            }

            queryString = "http://www.google.com/ig/api?weather=" + PostalCode;
        } else {
            queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity;
            WeatherData.locationName = Preferences.weatherCity;
        }

        URL url = new URL(queryString.replace(" ", "%20"));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);
        xr.parse(new InputSource(url.openStream()));
        WeatherSet ws = gwh.getWeatherSet();
        WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

        ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

        int days = conditions.size();
        WeatherData.forecast = new Forecast[days];

        for (int i = 0; i < days; ++i) {
            WeatherForecastCondition wfc = conditions.get(i);

            WeatherData.forecast[i] = m.new Forecast();
            WeatherData.forecast[i].day = null;

            WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition());
            WeatherData.forecast[i].day = wfc.getDayofWeek();

            if (Preferences.weatherCelsius) {
                WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString();
                WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString();
            } else {
                WeatherData.forecast[i].tempHigh = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                WeatherData.forecast[i].tempLow = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
            }
        }

        WeatherData.celsius = Preferences.weatherCelsius;

        String cond = wcc.getCondition();
        WeatherData.condition = cond;

        if (Preferences.weatherCelsius) {
            WeatherData.temp = Integer.toString(wcc.getTempCelcius());
        } else {
            WeatherData.temp = Integer.toString(wcc.getTempFahrenheit());
        }

        cond = cond.toLowerCase();

        WeatherData.icon = getIconGoogleWeather(cond);
        WeatherData.received = true;
        WeatherData.timeStamp = System.currentTimeMillis();

        Idle.updateIdle(context, true);
        MetaWatchService.notifyClients();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

}

From source file:com.mainpanel.LifeApp_Map.java

/**
 * Button to get current Location. This demonstrates how to get the current Location as required
 * without needing to register a LocationListener.
 * @throws IOException /*from  www.  j  ava2 s.c  o  m*/
 */
public void showMyLocation(View view) throws IOException {
    String location_name = "unknown";
    if (mLocationClient != null && mLocationClient.isConnected()) {
        onMyLocationButtonClick();

        String msg = "";
        my_lat = mLocationClient.getLastLocation().getLatitude();
        my_longi = mLocationClient.getLastLocation().getLongitude();

        //            my_lat = 40.6944;
        //            my_longi = -73.9865;

        //get address from Latitude and Longitude
        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = gcd.getFromLocation(my_lat, my_longi, 100);
        if (addresses.size() > 0 && addresses != null) {
            msg = "Address : " + addresses.get(0).getFeatureName() + "-" + addresses.get(0).getLocality() + "-"
                    + addresses.get(0).getAdminArea() + "-" + addresses.get(0).getCountryName();
            location_name = addresses.get(0).getFeatureName() + "-" + addresses.get(0).getLocality() + "-"
                    + addresses.get(0).getAdminArea() + "-" + addresses.get(0).getCountryName();
        }

        msg += "\nLatitude : " + my_lat;
        msg += "\nLongitude : " + my_longi;

        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
    Log.d("mymap", "In showMyLocation");

}

From source file:me.trashout.fragment.CollectionPointDetailFragment.java

/**
 * setup collection point data/*from ww  w  .  ja  v a  2  s  .co  m*/
 *
 * @param collectionPoint
 */
private void setupCollectionPointData(CollectionPoint collectionPoint) {
    if (isAdded()) {
        collectionPointDetailName
                .setText(collectionPoint.getSize().equals(Constants.CollectionPointSize.DUSTBIN)
                        ? getString(Constants.CollectionPointSize.DUSTBIN.getStringResId())
                        : collectionPoint.getName());

        collectionPointDetailType.setText(Html.fromHtml(
                getString(R.string.recyclable_gray, getString(R.string.collectionPoint_detail_mobile_recycable))
                        + TextUtils.join(", ", Constants.CollectionPointType
                                .getCollectionPointTypeNameList(getContext(), collectionPoint.getTypes()))));
        collectionPointDetailDistance
                .setText(String.format(getString(R.string.distance_away_formatter),
                        lastPosition != null ? PositionUtils.getFormattedComputeDistance(getContext(),
                                lastPosition, collectionPoint.getPosition()) : "?",
                        getString(R.string.global_distanceAttribute_away)));
        collectionPointDetailPosition
                .setText(collectionPoint.getPosition() != null
                        ? PositionUtils.getFormattedLocation(getContext(),
                                collectionPoint.getPosition().latitude, collectionPoint.getPosition().longitude)
                        : "?");

        if (collectionPoint.getOpeningHours() == null || collectionPoint.getOpeningHours().isEmpty()) {
            collectionPointDetailOpeningHoursContainer.setVisibility(View.GONE);
            collectionPointDetailOpeningHours.setVisibility(View.GONE);
        } else {
            collectionPointDetailOpeningHoursContainer.setVisibility(View.VISIBLE);
            collectionPointDetailOpeningHoursContainer.removeAllViews();
            collectionPointDetailOpeningHours.setVisibility(View.VISIBLE);
            for (Map<String, List<OpeningHour>> openingHoursMap : collectionPoint.getOpeningHours()) {
                for (Map.Entry<String, List<OpeningHour>> openingHourEntry : openingHoursMap.entrySet()) {
                    LinearLayout openingHoursLayout = (LinearLayout) getLayoutInflater()
                            .inflate(R.layout.item_opening_hours, null);
                    TextView dayNameTextView = openingHoursLayout.findViewById(R.id.txt_day_name);
                    TextView openingHoursTextView = openingHoursLayout.findViewById(R.id.txt_opening_hours);

                    int dayNameResId;
                    switch (openingHourEntry.getKey()) {
                    case "Monday":
                        dayNameResId = R.string.global_days_Monday;
                        break;
                    case "Tuesday":
                        dayNameResId = R.string.global_days_Tuesday;
                        break;
                    case "Wednesday":
                        dayNameResId = R.string.global_days_Wednesday;
                        break;
                    case "Thursday":
                        dayNameResId = R.string.global_days_Thursday;
                        break;
                    case "Friday":
                        dayNameResId = R.string.global_days_Friday;
                        break;
                    case "Saturday":
                        dayNameResId = R.string.global_days_Saturday;
                        break;
                    case "Sunday":
                        dayNameResId = R.string.global_days_Sunday;
                        break;
                    default:
                        dayNameResId = R.string.global_days_Monday;
                    }

                    dayNameTextView.setText(getString(dayNameResId));
                    for (OpeningHour openingHour : openingHourEntry.getValue()) {
                        String startString = String.valueOf(openingHour.getStart());
                        String finishString = String.valueOf(openingHour.getFinish());
                        if (startString.length() == 3) {
                            startString = "0" + startString;
                        }
                        if (finishString.length() == 3) {
                            finishString = "0" + finishString;
                        }
                        openingHoursTextView.append(startString.substring(0, 2) + ":"
                                + startString.substring(2, startString.length()) + " - "
                                + finishString.substring(0, 2) + ":"
                                + finishString.substring(2, finishString.length()) + ", ");
                    }
                    if (openingHourEntry.getValue().size() > 0) {
                        openingHoursTextView.setText(openingHoursTextView.getText().toString().substring(0,
                                openingHoursTextView.getText().length() - 2));
                    }
                    collectionPointDetailOpeningHoursContainer.addView(openingHoursLayout);
                }
            }
        }
        collectionPointDetailNote.setText(collectionPoint.getNote());

        if (collectionPoint.getPhone() == null || collectionPoint.getPhone().isEmpty()) {
            collectionPointDetailPhoneLayout.setVisibility(View.GONE);
        } else {
            collectionPointDetailPhoneLayout.setVisibility(View.VISIBLE);
            collectionPointDetailPhone.setText(collectionPoint.getPhone());
        }
        if (collectionPoint.getEmail() == null || collectionPoint.getEmail().isEmpty()) {
            collectionPointDetailEmailLayout.setVisibility(View.GONE);
        } else {
            collectionPointDetailEmailLayout.setVisibility(View.VISIBLE);
            collectionPointDetailEmail.setText(collectionPoint.getEmail());
        }

        if (collectionPoint.getGps() != null && collectionPoint.getGps().getArea() != null
                && !TextUtils.isEmpty(collectionPoint.getGps().getArea().getFormatedLocation())) {
            collectionPointDetailPlace.setText(collectionPoint.getGps().getArea().getFormatedLocation());
        } else {
            Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
            new GeocoderTask(geocoder, collectionPoint.getGps().getLat(), collectionPoint.getGps().getLng(),
                    new GeocoderTask.Callback() {
                        @Override
                        public void onAddressComplete(GeocoderTask.GeocoderResult geocoderResult) {
                            if (!TextUtils.isEmpty(geocoderResult.getFormattedAddress())) {
                                collectionPointDetailPlace.setText(geocoderResult.getFormattedAddress());
                            } else {
                                collectionPointDetailPlace.setVisibility(View.GONE);
                            }
                        }
                    }).execute();
        }
    }
}