2013-11-09 56 views
0

我在我的android代碼中使用谷歌地圖,我想要使用「地理編碼器」類獲取我的位置的地址。NullPointerException當使用谷歌地圖,android

這是我使用

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) 
+0

哪裏是loc?.. – amalBit

+0

發表您的logcat error.Nd完整代碼。 –

+0

位置爲空我認爲所以請發佈您的相關代碼... –

回答

0

我發現了另一個問題,這些問題會在您使用的代碼與某些設備發生的情況下發生,並且與使用getFromLocation方法的一行有關。不幸的是,這是一個與更新後的Google play服務有關的android操作系統相關的錯誤,主要發現於4.1.X設備中。唯一真正的解決方案是重新啓動手機並再次運行應用程序以啓用geocodsr。在某些情況下,getFromLocation()方法將返回服務不可用的錯誤。這不是一個真正的解決方案,而是關於geocoder的唯一解決方法。我做了無數個小時的研究,試圖爲自己解決這個問題,因爲它可以在某些手機上工作,而不是在其他手機上工作,並且只發現重新啓動手機將啓用它,但隨着時間的推移,錯誤將顯示,因此需要用戶再次重新引導。

這是不方便的,所以做一個嘗試catch語句,如果geocoder不工作使用JSONobject。閱讀帖子#13,瞭解JSONObject的解決方法。 http://code.google.com/p/android/issues/detail?id=38009 祝你好運。

+0

我解決了這個異常,但現在我得到了一個非常錯誤的結果!它告訴我,我在印度! –

+0

用什麼方法解決異常? – ChallengeAccepted

+0

我剛剛更改了這一行 'String s = longitude +「\ n」+ latitude + \t「\ n \ n我的Currrent城市是:」+ cityName;' 到這一行: 'String s = cityName;' –

相關問題