Android 获取当前位置..在地图上很好..但无法获取地址

Android 获取当前位置..在地图上很好..但无法获取地址,android,android-actionbar,geocoding,Android,Android Actionbar,Geocoding,实际上,我正在使用geocoder获取地址..但我获取的地址值为null。根据我的说法,我编写了正确的代码,以从getAddress()和address()等方法获取当前位置。我使用的代码如下: public class CurrentLoc extends Activity { // latitude and longitude static double latitude ; static double longitude ; // Google Map private Google

实际上,我正在使用geocoder获取地址..但我获取的地址值为null。根据我的说法,我编写了正确的代码,以从getAddress()和address()等方法获取当前位置。我使用的代码如下:

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); 
        }
公共类CurrentLoc扩展活动{
//经纬度
静态双纬度;
静态双经度;
//谷歌地图
私人谷歌地图谷歌地图;
私人场所经理场所经理;
私人位置;
私有字符串val;
私有静态最终最短长\u距离\u更改\u用于\u更新=1;//以米为单位
私有静态最终最长最短\u更新间隔时间\u=1000;//以毫秒为单位
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.new3);
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
locationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序,
两次更新之间的最短时间,
用于更新的最小距离更改,
新建MyLocationListener()
);  
locationManager.requestLocationUpdates(locationManager.NETWORK_提供程序、更新之间的最短时间、更新的最短距离、新MyLocationListener());
getAddress();
试一试{
//装载图
initilizeMap();
}捕获(例外e){
e、 printStackTrace();
}
}
/**
*函数加载映射。如果未创建映射,它将为您创建映射
* */
公共字符串getAddress(){
location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序);
location=locationManager.getLastKnownLocation(locationManager.NETWORK\u提供程序);
如果(位置!=null){
纬度=位置。getLatitude();
longitude=location.getLongitude();
/*字符串消息=String.format(
“当前位置\n经度:%1$s\n纬度:%2$s”,
lat(液化天然气)*/
试一试{
val=地址(纬度、经度);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
Toast.makeText(CurrentLoc.this,val,
Toast.LENGTH_LONG).show();
}
返回val;
}      
公共字符串地址(双lt,双lg)引发IOException{
地理编码器;
列出地址;
geocoder=新的geocoder(这个,Locale.getDefault());
地址=地理编码器。getFromLocation(lt,lg,1);
字符串地址=地址.get(0).getAddressLine(0);
字符串city=addresses.get(0).getAddressLine(1);
字符串country=addresses.get(0).getAddressLine(2);
返回地址+“\n”+城市+“\n”+国家;
}       
私有类MyLocationListener实现LocationListener{
已更改位置上的公共无效(位置){
字符串消息=String.format(
“新位置\n经度:%1$s\n纬度:%2$s”,
location.getLength(),location.getLatitude()
);
//Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG.show();
}
状态已更改的公共void(字符串s、整数i、束b){
Toast.makeText(CurrentLoc.this,“提供者状态已更改”,
Toast.LENGTH_LONG).show();
}
公共无效onProviderDisabled(字符串s){
Toast.makeText(当前位置为this,
“用户禁用了提供程序。GPS已关闭”,
Toast.LENGTH_LONG).show();
}
已提供已启用的公共void(字符串s){
Toast.makeText(当前位置为this,
“由用户启用提供程序。GPS已打开”,
Toast.LENGTH_LONG).show();
}
}
私有void initilizeMap(){
if(googleMap==null){
googleMap=((MapFragment)getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition CameraPosition=新建CameraPosition.Builder().target(
新的LatLng(location.getLatitude(),location.getLongitude()).zoom(12.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
MarkerOptions marker=newmarkeroptions().position(新LatLng(location.getLatitude(),location.getLongitude()).title(“你好地图”);
谷歌地图。添加标记(标记);
isMyLocationEnabled();
//检查是否成功创建映射
if(googleMap==null){
Toast.makeText(getApplicationContext(),
“抱歉!无法创建地图”,Toast.LENGTH\u SHORT)
.show();
}
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
MenuInflater充气机=getMenuInflater();
充气机。充气(R.menu.mnew1,menu);
返回super.onCreateOptions菜单(菜单);
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目上的按下
开关(item.getItemId()){
案例R.id.home:
openSearch();
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
私有void openSearch(){
字符串val1=null;
val1=getAddress();
Intent intnt=新的Intent(getApplicationContext(),SendSms.class);
内部额外费用(“loct”,val1);
星触觉(intnt);
}
}移动代码:

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

    value=address(latitude, longitude);

    Toast.makeText( CurrentLoc.this, value,
    Toast.LENGTH_LONG).show();
 }
在您的
public void onLocationChanged(Location-Location)
方法中

当您请求一个新位置时,您不会立即得到结果。相反,您需要注册一个侦听器,就像您调用
locationManager.requestLocationUpdates
时所做的那样