我的应用程序在onLocationChanged()之后崩溃了一段时间,

时间:2016-05-11 08:55:10

标签: android locationmanager

这是我的LocationListener ...我希望我的位置监听器只获取一次城市,并将其存储到共享首选项中,然后我想将该位置用于其他目的。所有工作都很好,但它会在一段时间后崩溃

loclistener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
                List<Address> addresses = null;
                try {
                    addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                cityName = addresses.get(0).getLocality();
                //tvLoc.append("\n" + addresses.get(0).getLocality());
                tvLoc.setText(cityName);
                editor.putString(CITYNAME,cityName);
               // Toast.makeText(Emergencylist.this,"CityName saved :"+cityName, Toast.LENGTH_LONG).show();
                editor.commit();


            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);


            }
        };

1 个答案:

答案 0 :(得分:1)

此代码危险: 如果发生异常...... 地址 NULL

 List<Address> addresses = null;
                try {
                    addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                cityName = addresses.get(0).getLocality();

避免意外崩溃的解决方案:

     public void onLocationChanged(Location location) {

                    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    if((addresses && addresses.isEmpty()) || !addresses) { return; }
                    cityName = addresses.get(0).getLocality();
                    tvLoc.setText(cityName);                                         editor.putString(CITYNAME,cityName);                   
                    editor.commit();

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