Techrens Alert – part 4

Techrens Alert – part 4

So we are making good progress with the application. Now that we are able to get the location to display on the map, we now need to get a normal address for those coordinates.

Part 4

The changes were pretty easy for this part, see code below (pay close attention to blue highlights)

public class TestActivity1 extends AppCompatActivity implements LocationListener {

    LocationManager locationManager;
    String mprovider;
    Location location;
    TextView message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test1);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        message = (TextView) findViewById(R.id.txtMessage);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        final Button button = (Button) findViewById(R.id.btnCheckGps);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getLocation();
            }
        });


        final Button openLink = (Button) findViewById(R.id.btnOpenLink);
        openLink.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (location != null) {

                    getGeoInfo();
                    getUrl();

                }
                //
            }
        });

    }

    private void getGeoInfo(){

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

        try {

            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            String addressText = address + " " + city + ", " + state;
            message.setText(addressText);

            Toast.makeText(getBaseContext(), addressText, Toast.LENGTH_LONG).show();
        }
        catch (IOException e) {

        }

    }

    private void getUrl(){

        String myUrl = "http://maps.google.com/maps?q=" + location.getLatitude() + "," + location.getLongitude();

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myUrl));
        startActivity(browserIntent);

    }

    private void getLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        mprovider = locationManager.getBestProvider(criteria, false);

        if (mprovider != null && !mprovider.equals("")) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            location = locationManager.getLastKnownLocation(mprovider);
            locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

            if (location != null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_test_activity1, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(Location location) {

        message.setText("Current Longitude:" + location.getLongitude() +  "\n\nCurrent Latitude:" + location.getLatitude());

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }


}

First thing I did was make the message textview a global variable so that I am not constantly recreating it and initializing it. Next I created the getGeoInfo method that gets the address from the longitude and latitude. Once I have the address information, I put the information I want into a variable name addressText. I then output the variable on the message textview, and display it as a toast pop-up for extra effect.

So now we have a valid address to go with our longitude and latitude 🙂 This is exciting 😉

If you have been following along you can make the changes to your project, or you can download the apk below.

Tell me what you think so far in the comment section below. Also see if you can break it!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *