LocationManager没有得到正确的结果 [英] LocationManager don't get the right results

查看:108
本文介绍了LocationManager没有得到正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LocationManager从土地增值税,隆基获得城市名称转换,但我得到错误的结果,我觉得有什么不对这个code在这里:

  locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //定义标准如何选择locatioin提供商 - >使用
        // 默认
        标准标准=新标准();
        供应商= locationManager.getBestProvider(标准,FALSE);
        位置位置= locationManager.getLastKnownLocation(供应商);

        //初始化位置字段
        如果(位置!= NULL){
          的System.out.println(提供者+提供商+已被选定。);
          onLocationChanged(位置);
          Log.d(msgh,msgh);
        } 其他 {
             的System.out.println(位置不可用);
            Log.d(味精,味精);
        }
 

在code不进入if语句,总是进入else语句。

编辑之后,这是logcat的:

  11-24 15:06:25.072:E / AndroidRuntime(6963):致命异常:主要
11-24 15:06:25.072:E / AndroidRuntime(6963):java.lang.RuntimeException的:无法启动的活动ComponentInfo {com.survivingwithandroid.weatherapp / com.survivingwithandroid.weatherapp.MainActivity}:显示java.lang.NullPointerException
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1256)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.os.Handler.dispatchMessage(Handler.java:99)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.os.Looper.loop(Looper.java:137)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread.main(ActivityThread.java:5103)
11-24 15:06:25.072:E / AndroidRuntime(6963):在java.lang.reflect.Method.invokeNative(本机方法)
11-24 15:06:25.072:E / AndroidRuntime(6963):在java.lang.reflect.Method.invoke(Method.java:525)
11-24 15:06:25.072:E / AndroidRuntime(6963):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
11-24 15:06:25.072:E / AndroidRuntime(6963):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 15:06:25.072:E / AndroidRuntime(6963):在dalvik.system.NativeStart.main(本机方法)
11-24 15:06:25.072:E / AndroidRuntime(6963):由:显示java.lang.NullPointerException
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.location.Geo coderParams< INIT>(GEO coderParams.java:50)。
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.location.Geo $ C $为CR INIT>(GEO coder.java:83)。
11-24 15:06:25.072:E / AndroidRuntime(6963):在com.survivingwithandroid.weatherapp.MainActivity.onCreate(MainActivity.java:227)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.Activity.performCreate(Activity.java:5133)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-24 15:06:25.072:E / AndroidRuntime(6963):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
 

解决方案

下面是获得位置的完整code。这code会自动给你提供最好的供应商(GPS或网络)。此外,它不会给你的最后一个已知的位置,但在当前的位置。

 保护字符串currentLatitude,currentLongitude;
双纬度,经度;
保护LocationManager locationManager;
私人LocationListener的LL;
locationManager =(LocationManager)getSystemService(
            Context.LOCATION_SERVICE);
    如果(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){

            Toast.makeText(这一点,
                    GPS功能的。寻找精确的位置。
                    Toast.LENGTH_SHORT).show();
        LL =新GpsListener();
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,0,0,LL);

    } 其他 {
        如果(locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

                Toast.makeText(这一点,
                        GPS禁用。寻找粗糙位置。
                        Toast.LENGTH_SHORT).show();
            LL =新GpsListener();
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,0,0,LL);

        } 其他 {
            Toast.makeText(这一点,
                    启用位置设置,以获得当前的位置。
                    Toast.LENGTH_LONG).show();

        }
    }

私有类GpsListener实现LocationListener的{

    公共无效onLocationChanged(位置定位){
        // TODO自动生成方法存根
        如果(位置!= NULL){
            尝试 {
                Toast.makeText(getApplicationContext(),发现地点,
                        Toast.LENGTH_SHORT).show();
            }赶上(例外五){

            }

            纬度= location.getLatitude();
            LON = location.getLongitude();
                            地理codeR GCD =新的地缘codeR(背景下,Locale.getDefault());
                            尝试{
                            名单<地址>地址= gcd.getFromLocation(纬度,经度,1);
                            如果(addresses.size()大于0)
                            串的cityName = addresses.get(0).getLocality();
                            }
                             赶上(IOException异常E){}
                             赶上(NullPointerException异常E){}
            currentLatitude = Double.toString(LAT);
            currentLongitude = Double.toString(LON);
            尝试 {
                如果(LL!= NULL)
                    locationManager.removeUpdates(Ⅱ);
            }赶上(例外五){

            }

            locationManager = NULL;

        } 其他 {
            Toast.makeText(getApplicationContext(),找不到位置,
                    Toast.LENGTH_LONG).show();

        }

    }

    公共无效onProviderDisabled(字符串提供商){
        // TODO自动生成方法存根

    }

    公共无效onProviderEnabled(字符串提供商){
        // TODO自动生成方法存根

    }

    公共无效onStatusChanged(字符串商,INT地位,捆绑演员){
        // TODO自动生成方法存根

    }

类} //结束
 

编辑 - 一定要具有以下权限在你的Andr​​oid清单:

  android.permission.INTERNET对

android.permission.ACCESS_NETWORK_STATE

android.permission.ACCESS_COARSE_LOCATION

android.permission.ACCESS_FINE_LOCATION
 

I am using LocationManager to convert from lat,longi to get the city name, but I am getting wrong results, I think there is something wrong in this code here:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
          Log.d("msgh","msgh");
        } else {
             System.out.println("location not available");
            Log.d("msg","msg");
        }

the code doesn't enter the if statement and always enters the else statement.

after Editing, this is the logCat:

11-24 15:06:25.072: E/AndroidRuntime(6963): FATAL EXCEPTION: main
11-24 15:06:25.072: E/AndroidRuntime(6963): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.survivingwithandroid.weatherapp/com.survivingwithandroid.weatherapp.MainActivity}: java.lang.NullPointerException
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.os.Looper.loop(Looper.java:137)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at java.lang.reflect.Method.invoke(Method.java:525)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at dalvik.system.NativeStart.main(Native Method)
11-24 15:06:25.072: E/AndroidRuntime(6963): Caused by: java.lang.NullPointerException
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.location.Geocoder.<init>(Geocoder.java:83)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.survivingwithandroid.weatherapp.MainActivity.onCreate(MainActivity.java:227)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.Activity.performCreate(Activity.java:5133)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

解决方案

Here is the full code of getting location. This code will automatically give you the best provider available(GPS or Network). Moreover, it won't give you the last known location but the current location.

protected String currentLatitude, currentLongitude;
double lat, lon;
protected LocationManager locationManager;
private LocationListener ll;
locationManager = (LocationManager) getSystemService(
            Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            Toast.makeText(this,
                    "GPS enabled. Finding fine location. ",
                    Toast.LENGTH_SHORT).show();
        ll = new GpsListener();
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, ll);

    } else {
        if (locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

                Toast.makeText(this,
                        "GPS disabled. Finding coarse location.",
                        Toast.LENGTH_SHORT).show();
            ll = new GpsListener();
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0, ll);

        } else {
            Toast.makeText(this,
                    "Enable location settings to get current location.",
                    Toast.LENGTH_LONG).show();

        }
    }

private class GpsListener implements LocationListener {

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null) {
            try {
                Toast.makeText(getApplicationContext(), "Location Found",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {

            }

            lat = location.getLatitude();
            lon = location.getLongitude();
                            Geocoder gcd = new Geocoder(context, Locale.getDefault());
                            try{
                            List<Address> addresses = gcd.getFromLocation(lat, lon, 1);
                            if (addresses.size() > 0) 
                            String cityName=addresses.get(0).getLocality();
                            }
                             catch (IOException e) {}
                             catch (NullPointerException e) {}
            currentLatitude = Double.toString(lat);
            currentLongitude = Double.toString(lon);
            try {
                if (ll != null)
                    locationManager.removeUpdates(ll);
            } catch (Exception e) {

            }

            locationManager = null;

        } else {
            Toast.makeText(getApplicationContext(), "No Location Found",
                    Toast.LENGTH_LONG).show();

        }

    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}// end of Class

Edit- Be sure to have the following permissions in your Android Manifest:

android.permission.INTERNET

android.permission.ACCESS_NETWORK_STATE

android.permission.ACCESS_COARSE_LOCATION

android.permission.ACCESS_FINE_LOCATION

这篇关于LocationManager没有得到正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆