Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用谷歌地图、android时的NullPointerException_Android_Google Maps - Fatal编程技术网

使用谷歌地图、android时的NullPointerException

使用谷歌地图、android时的NullPointerException,android,google-maps,Android,Google Maps,我在android代码中使用谷歌地图,我想使用“Geocoder”类获取我所在位置的地址 这是我正在使用的代码 Geocoder geocoder; List<Address> addresses = null; geocoder = new Geocoder(this, Locale.getDefault()); try { addresses = geocoder.getFromLocation(loc.getLatitude(), loc

我在android代码中使用谷歌地图,我想使用“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();
    }
这是完整的代码

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

    }






}

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

这是不方便的,所以请执行try-catch语句,如果地理编码器不工作,请使用JSONobject。阅读第13篇文章,了解JSONObject的解决方法。
祝你好运。

发布你的logcat错误。Nd完整代码。位置为空。我想是的,请发布你的相关代码…我想网络有问题吗?hv u添加了权限?尝试使用静态位置进行测试。。如果测试成功,则您的案例中存在空位置。@amalBit我编辑了问题我解决了异常,但现在我得到了一个非常错误的结果!!它告诉我我在印度!!我刚刚更改了此行“字符串s=经度+”\n“+纬度+”\n\n我当前所在的城市是:“+cityName;”到此行:'String s=cityName;'如果它告诉你你在印度,而你在其他地方,你可能把lat换成了lng;)哈哈哈,看起来迈克尔一语中的。@MichałK我不认为这是问题所在,因为我所在地的经纬度与印度完全不同,即使在切换经纬度时!!
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

    }






}
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)