0

我在我的 android 代码中使用 Google 地图,我想使用“Geocoder”类获取我的位置地址。

这是我正在使用的代码

Geocoder geocoder;
    List<Address> addresses = null;
    geocoder = new Geocoder(this, Locale.getDefault());
    try {
        addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但我在这一行得到一个 NullPointerException :

addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);

这是完整的代码

public class MainActivity extends Activity  implements LocationListener {


    private TextView cityText;
    private TextView condDescr;
    private TextView temp;
    private TextView press;
    private TextView windSpeed;
    private TextView windDeg;

    private TextView hum;
    private ImageView imgView;
    Geocoder geocoder;
    String bestProvider;
    List<Address> user = null;
    double lat;
    double lng;
   public static String resultStr;
    private String latituteField;
    private String longitudeField;
    private LocationManager locationManager;
    private String provider;
    public String cityName;
    public Location loc;
    @Override
    public void onLocationChanged(android.location.Location loc) {
        // TODO Auto-generated method stub
         String longitude = "Longitude: " +loc.getLongitude();  
        //  Log.v(TAG, longitude);
            String latitude = "Latitude: " +loc.getLatitude();
            //Log.v(TAG, latitude);
    //String 
        cityName=null;                
          Geocoder gcd = new Geocoder(getBaseContext(),   
       Locale.getDefault());               
          List<Address>  addresses;    
          try {    
          addresses = gcd.getFromLocation(loc.getLatitude(), loc  
       .getLongitude(), 1);    
          if (addresses.size() > 0)    
             System.out.println(addresses.get(0).getLocality());    
             cityName=addresses.get(0).getLocality();    
            } catch (IOException e) {              
            e.printStackTrace();    
          }   

          String s = longitude+"\n"+latitude +  
       "\n\nMy Currrent City is: "+cityName;  
              // editLocation.setText(s);  
            }  




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("hi","hi");


        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        Log.d("addresses",addresses.toString());

        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);
        android.location.Location location = locationManager.getLastKnownLocation(provider);

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

        }

    //  String city ="lat=%f&lon=%f,"  

        /////////////////////////
        cityText = (TextView) findViewById(R.id.cityText);
        condDescr = (TextView) findViewById(R.id.condDescr);
        temp = (TextView) findViewById(R.id.temp);
        hum = (TextView) findViewById(R.id.hum);
        press = (TextView) findViewById(R.id.press);
        windSpeed = (TextView) findViewById(R.id.windSpeed);
        windDeg = (TextView) findViewById(R.id.windDeg);
        imgView = (ImageView) findViewById(R.id.condIcon);

        JSONWeatherTask task = new JSONWeatherTask();
        //task.execute(new String[]{city});
        task.execute(new String[]{cityName});
    }

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


    private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

        @Override
        protected Weather doInBackground(String... params) {
            Weather weather = new Weather();
            String data = ( (new WeatherHttpClient()).getWeatherData(params[0]));

            try {
                weather = JSONWeatherParser.getWeather(data);

                // Let's retrieve the icon
                weather.iconData = ( (new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));

            } catch (JSONException e) {             
                e.printStackTrace();
            }
            return weather;

    }





    @Override
        protected void onPostExecute(Weather weather) {         
            super.onPostExecute(weather);

            if (weather.iconData != null && weather.iconData.length > 0) {
                Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length); 
                imgView.setImageBitmap(img);
            }

            cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
            condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
            temp.setText("" + Math.round((weather.temperature.getTemp() - 275.15)) + "°C");
            hum.setText("" + weather.currentCondition.getHumidity() + "%");
            press.setText("" + weather.currentCondition.getPressure() + " hPa");
            windSpeed.setText("" + weather.wind.getSpeed() + " mps");
            windDeg.setText("" + weather.wind.getDeg() + "°");

        }







  }


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

    }

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

    }

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

    }






}

这是logCat:

11-09 04:30:55.723: E/AndroidRuntime(1868): FATAL EXCEPTION: main
11-09 04:30:55.723: E/AndroidRuntime(1868): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.survivingwithandroid.weatherapp/com.survivingwithandroid.weatherapp.MainActivity}: java.lang.NullPointerException
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.os.Looper.loop(Looper.java:137)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at java.lang.reflect.Method.invokeNative(Native Method)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at java.lang.reflect.Method.invoke(Method.java:525)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at dalvik.system.NativeStart.main(Native Method)
11-09 04:30:55.723: E/AndroidRuntime(1868): Caused by: java.lang.NullPointerException
11-09 04:30:55.723: E/AndroidRuntime(1868):     at com.survivingwithandroid.weatherapp.MainActivity.onCreate(MainActivity.java:127)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.Activity.performCreate(Activity.java:5133)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-09 04:30:55.723: E/AndroidRuntime(1868):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
4

1 回答 1

0

我发现了另一个问题,该问题将在某些设备上使用您使用的代码发生,它也与使用 getFromLocation 方法的一行有关。不幸的是,这是一个与 android OS 相关的错误,它与更新的 Google Play 服务相关,主要存在于 4.1.X 设备中。唯一真正的解决方案是重新启动手机并再次运行应用程序以启用 geocodsr。在某些情况下,您的 getFromLocation() 方法将返回服务不可用的错误。这并不是真正的解决方案,而是有关地理编码器的唯一解决方法。我进行了无数小时的研究,试图为自己解决这个问题,因为它可以在某些手机上运行,​​而不能在其他手机上运行,​​并且只发现重启手机会启用它,但随着时间的推移,错误会出现,因此需要用户再次重启.

这很不方便,所以改为使用 try catch 语句,如果地理编码器不起作用,请使用 JSONobject。阅读第 13 篇文章,了解 JSONObject 的解决方法。 http://code.google.com/p/android/issues/detail?id=38009 祝你好运。

于 2013-11-09T09:57:07.037 回答