s137
s137

Reputation: 41

Android: Googe Map is null although initialized

I have a Maps Fragment with a MapView inside. I initialise a Google Map Object in the onMapReady Method and the marker I set in this method at the beginning works fine. But as soon as I want to modify the marker or set a new one in another custom Method, I get a NullPointerException saying that my googleMap object is null. Which it should not be due to the fact that it has been already initialised.

Your help would be very much appreciated. Thank you very much in advance.

Here's my code:

This is what the beginning ofmy fragment activity looks like:

public class MapsFragment extends Fragment implements OnMapReadyCallback {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_maps, container, false);

    mMapView = (MapView) rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    mMapView.getMapAsync(this);

    return rootView;
}

This is the onMapReady Method:

@Override
public void onMapReady(GoogleMap gMap) {
    // The global variable googleMap gets initialised
    googleMap = gMap;
    LatLng sydney = new LatLng(-33.852, 151.211);
    googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

This is my custom user called method:

 public void updateCamera(String search_string) {

   LatLng search_string_place = new LatLng(-37.9712371, 144.4927088);

   // THIS is where the NullPointer exception happens for the first time
   googleMap.addMarker(new 
   MarkerOptions().position(search_string_place).title(Melbourne));

   googleMap.moveCamera(CameraUpdateFactory.newLatLng(search_string_place)); 
 }

All methods are in the same class: MapsFragment

Edit:

Error Log:

FATAL EXCEPTION: main
Process: <packagename>, PID: 26556
java.lang.IllegalStateException: Could not execute method of the activity
  at android.view.View$1.onClick(View.java:3830)
  at android.view.View.performClick(View.java:4445)
  at android.view.View$PerformClick.run(View.java:18446)
  at android.os.Handler.handleCallback(Handler.java:733)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5146)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
  at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at android.view.View$1.onClick(View.java:3825)
  ... 11 more
Caused by: java.lang.NullPointerException
  at <packagename>.MapsFragment.updateCamera(MapsFragment.java:134)
  at <packagename>.MainActivity.callUpdateCamera(MainActivity.java:46)
  ... 14 more

My manifest file:

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name="android.support.multidex.MultiDexApplication">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

</application>

EDIT:

I solved the problem by just putting everything in one class/activity. Then all the calls worked fine. I think the problem was that I created a new instance of the MapsFragment and in this new instance the global var googleMap was undefined.

Thank you very much for all the answers.

Upvotes: 2

Views: 1461

Answers (2)

Dhananjay P
Dhananjay P

Reputation: 11

Had the same problem, it worked when I changed GoogleMap object to static

Upvotes: 1

Carmen
Carmen

Reputation: 181

I don't know where you call your custom method, but you could try to pass the initialized map to your method to be sure you can access it.

Try this:

public void updateCamera(String search_string, GoogleMap googleMap) {

   LatLng search_string_place = new LatLng(-37.9712371, 144.4927088);

   // THIS is where the NullPointer exception happens for the first time
   googleMap.addMarker(new 
   MarkerOptions().position(search_string_place).title(Melbourne));

   googleMap.moveCamera(CameraUpdateFactory.newLatLng(search_string_place)); 
 }

Upvotes: 0

Related Questions