0

Actually i am using geocoder to get the address..but i am getting address value as null.According to me I wrote the correct code to get current location from methods like getAddress() and address().The code i used is as following:

public class CurrentLoc extends Activity {

// latitude and longitude
static double latitude ;
static double longitude ;

  // Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private Location location;
private String val;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new3);
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );  
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());

        getAddress();

    try {
        // Loading map
        initilizeMap();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * function to load map. If map is not created it will create it for you
 * */

public String  getAddress(){

       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
        if (location != null) {
            latitude= location.getLatitude();
            longitude= location.getLongitude();

            /*String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    lat, lng);*/


        try {
            val = address(latitude, longitude);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


            Toast.makeText( CurrentLoc.this, val,
                    Toast.LENGTH_LONG).show();
        }
        return val;
    }      

    public String address(double lt,double lg) throws IOException{
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
        addresses = geocoder.getFromLocation(lt, lg, 1);

        String address = addresses.get(0).getAddressLine(0);
        String city = addresses.get(0).getAddressLine(1);
        String country = addresses.get(0).getAddressLine(2);
        return address +"\n"+ city +"\n"+ country;
    }       






    private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
     //   Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(CurrentLoc.this, "Provider status changed",
               Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(CurrentLoc.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(CurrentLoc.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

    }



private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
        googleMap.addMarker(marker);
        googleMap.isMyLocationEnabled();
        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.mnew1, menu);

            return super.onCreateOptionsMenu(menu);
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle presses on the action bar items
            switch (item.getItemId()) {
                case R.id.home:

                    openSearch();

                    return true;          
            default:
                    return super.onOptionsItemSelected(item);
            }
            }

        private void openSearch(){

            String val1 = null;

                val1 = getAddress();

            Intent intnt=new Intent(getApplicationContext(),SendSms.class);

            intnt.putExtra("loct", val1);
            startActivity(intnt); 
        }

}

1 Answers1

0

Move your code:

if (location != null) {
    latitude= location.getLatitude();
    longitude= location.getLongitude();

    value=address(latitude, longitude);

    Toast.makeText( CurrentLoc.this, value,
    Toast.LENGTH_LONG).show();
 }

Inside your public void onLocationChanged(Location location) method.

When you request a new location, you don't get the result immediately. Instead, you need to register a listener, like you did when you called locationManager.requestLocationUpdates, so the location provider can notify it when it fetches a location for you.

Also, from what I understood from your code, you may benefit from calling locationManager.requestSingleUpdate if you just need to get the phone's address in the current location instead of constantly getting location updates that requestLocationUpdates will give you.

Finally, consider this blog post for best practices on fetching the user location. You don't always need to get location updates if the current location is already known.

Hope it helps.

Ricardo
  • 7,785
  • 8
  • 40
  • 60
  • i need to study about it now..i think..u told me so many things..thanks – user3101598 Dec 16 '13 at 09:08
  • @user3101598 let me know if the solution above works out for you. – Ricardo Dec 16 '13 at 09:16
  • @Ricardo..now facing a different problem..it showing default location on map..i getting confused now.. – user3101598 Dec 16 '13 at 09:31
  • @user3101598 You need to debug your code and post another question with detailed information about what exactly is happening. See this for some guidelines: http://stackoverflow.com/questions/how-to-ask – Ricardo Dec 16 '13 at 09:55
  • I'll put another...but as soon as i do this..people will start down voting me..thatsy iam ignoring it – user3101598 Dec 16 '13 at 10:14
  • @user3101598 If you don't mind a few tips: 1) You need to accept people's answers and upvote them if they help you. There is an arrow up and a tick mark to the top left of each answer for you to check. People will help you more if you acknowledge their help. I can see on your profile that you haven't accepted any answer. 2) You need to be specific on your questions and show your work. You can't just post all your code and expect people to do all the work for you. The link in my previous comment has some helpful notes on this. – Ricardo Dec 16 '13 at 10:16
  • none of that answer was correct..if i find something helpful..i replied with a thank you note..but i can't say it correct..as for a fact it was not correct..so can't upvote it..you can also have a look at it... – user3101598 Dec 16 '13 at 10:25
  • When I look at this case http://stackoverflow.com/questions/20604406/actionbar-not-working, they asked you something in the comments and you didn't reply. Plus both showed their effort to help you and you didn't upvote their answers. You don't have to accept if it's not correct but you can at least up vote to acknowledge their efforts. And you need to give them the feedback they are asking. – Ricardo Dec 16 '13 at 10:29
  • @user3101598 One more thing, if you fix the problem yourself, you need to come back to your questions and answer them yourself so other people can benefit from your solution. – Ricardo Dec 16 '13 at 10:32
  • yaa..thats the thing i miss..i'll definately answer to the question those i know the answer..thanks – user3101598 Dec 16 '13 at 10:38
  • @Ricardo..just answer a simple question is it possible to get current location in one activity and passing address from there to another activity – user3101598 Dec 16 '13 at 15:53
  • Yes, it is possible. Look at the blog post I mentioned in my answer: http://android-developers.blogspot.pt/2011/06/deep-dive-into-location.html. My suggestion is that you download the code there and make it run for you so you can understand what is going on. – Ricardo Dec 16 '13 at 15:57