2012-03-29 3 views
0

Это мой LocationActivity:MapView приближается к нулю, независимо от того, что я делаю в Android. Что может быть ошибкой?

public class LocationActivity extends MapActivity{ 

    GeoPoint p; 
    Bundle bundle; 

    ArrayList <String> address = new ArrayList<String>(); 

    MapController mc; 
    private LocationManager locationManager; 


    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.map); 

     MapView mapView = (MapView)findViewById(R.id.mapView1); 

     LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

     Criteria criteria = new Criteria(); 
      // criteria.setAccuracy(Criteria.ACCURACY_FINE); 
      criteria.setAltitudeRequired(false); 
      criteria.setBearingRequired(false); 
      criteria.setCostAllowed(true); 
      String strLocationProvider = lm.getBestProvider(criteria, true); 

     Location location = lm.getLastKnownLocation(strLocationProvider); 

     if (location == null) 
     { 
      Toast.makeText(LocationActivity.this, "working", Toast.LENGTH_LONG); 
     } 
     double lat = (double) location.getLongitude(); 
     double lon = (double) location.getLatitude(); 

     p = new GeoPoint(
       (int) (lat * 1E6), 
       (int) (lon * 1E6)); 

     mc = mapView1.getController(); 
     //  mc.setCenter(new GeoPoint(29450116, 77312191)); 
     mc.animateTo(p); 
     mapView1.setClickable(true); 
     mapView1.setBuiltInZoomControls(true); 
     mapView1.setSatellite(true); 
     mapView1.setTraffic(true); 

     mapView1.invalidate(); 

    } 

    @Override 
    protected boolean isRouteDisplayed() { 
    // TODO Auto-generated method stub 
    return false; 
    } 
} 

Это мой map.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

    <com.google.android.maps.MapView 
     android:id="@+id/mapView1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:enabled="true" 
     android:clickable="true" 
     android:apiKey="04KR0_lkSRZxCk_JC9yIkk50f3ZE_JjBT7HJ6jw" 
     /> 

    <Button 
     android:text="Add Location" 
     android:id="@+id/mapButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </Button> 
</RelativeLayout> 

Я очищено мой проект. Создал новый макет, чтобы проверить, работает ли он или нет, но все же мой MapView имеет значение null, и я получаю исключение нулевого указателя. Что может быть ошибкой?

+0

Можете вы pls сказать нам ясно, какая линия бросает NullPointerException. Также pls отправляет ваш logcat тоже. – AndroDev

+0

Это моя ошибка: mc = mapView1.getController(); – Hick

ответ

1

Я согласен с px3j; если у вас есть MapView mapView = (MapView)findViewById(R.id.mapView1); до MapView mapView1 = (MapView)findViewById(R.id.mapView1);, пожалуйста, обновите свой вопрос.

0

Похоже, вы назначаете mapView, но используете mapView1.

// Assigning the value to mapView 
    MapView mapView = (MapView)findViewById(R.id.mapView1); 

    // accessing mapView1 
    mc = mapView1.getController(); // Is this generating the NPE? 

Надеется, что это помогает ...

+0

Нет, я сделал изменения. Тем не менее он равен нулю. – Hick

+0

Проблема, скорее всего, что findViewByID не находит вид. Этот метод возвращает значение null, а не исключает исключение. Поместите точку останова на эту строку и осмотрите mapView после вызова. Это нулевое значение? Если да, разместите весь свой XML для своей деятельности. – Simon

+0

Отправили мой весь XML. – Hick

0

проверки getLastKnownLocation()

Бросками IllegalArgumentException, если поставщик является нулевым или не существует

вы должны использовать примерочные поймать блок:

mc = mapView.getController(); 
try { 
    Location location = lm.getLastKnownLocation(strLocationProvider); 
    if (location != null) { 
     double lat = (double) location.getLongitude(); 
     double lon = (double) location.getLatitude(); 
     p = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); 
     mc.animateTo(p); 
    } 
} catch (IllegalArgumentException e) { 
    e.printStackTrace(); 
} 

Ни один провайдер не был fou в соответствии с вашими критериями, вы должны их настроить.

+0

Также убедитесь, что вы установили разрешения INTERNET и ACCESS_FINE_LOCATION в файле манифеста. Также используется . – biegleux