Reputation: 466
I'm trying to run an app using Google maps v2, but the Logcat shows the error:
Fatal exception: main java.lang.RuntimeException: unable to start activity ComponentInfo{com.app.mapa/com.app.MapaLugares}: android.view.InflatException: java.lang.NullPointerException
Here is the code:
activity_mapa_lugares.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MapaLugares.java
package com.app.mapa;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Point;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.LatLng;
public class MapaLugares extends FragmentActivity {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa_lugares);
mMap = ((MapFragment) getFragmentManager().findFragmentById (R.id.mapa)).
getMap();
mMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
Projection proj = mMap.getProjection();
Point coord = proj.toScreenLocation(point);
Toast.makeText(MapaLugares.this, "Click\n" + "Lat: " +
point.latitude + "\n" + "Lng: "+ point.longitude+ "\n" + "X: "
+ coord.x + " - Y: "+ coord.y, Toast.LENGTH_SHORT)
.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mapa_lugares, menu);
return true;
}
}
What's wrong?
Thanks.
Upvotes: 0
Views: 591
Reputation: 41099
You are setting your map in the XML file to be of type: SupportMapFragment
:
android:name="com.google.android.gms.maps.SupportMapFragment"
But in your java code you are trying to get another object:
mMap = ((MapFragment) getFragmentManager().findFragmentById (R.id.mapa)).
getMap();
2 Problems here:
1. You need to fetch the SupportMapFragment
and not MapFragment
, like so:
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
2. You are trying to get the wrong id: in XML you gave the map the: `android:id="@+id/map"
while in code you are trying to get: (R.id.mapa)
and this is the wrong id.
Fix those issues and tell us what is the result.
You can also go over this blog post I wrote on Google Map API V2 to get a better idea on how to build an application that uses Google Map API V2:
Upvotes: 1