CraZyDroiD
CraZyDroiD

Reputation: 7105

Null pointer exception on adding a marker to google maps

I'm trying to add a marker to google maps in my android app.But i'm getting a null point exception when running the app.I don't see where my code could have gone wrong.

This is the code i've used

GoogleMap googleMap = null;

            MapFragment fm = (MapFragment) (activity.getFragmentManager())
                    .findFragmentById(R.id.map);

            googleMap = fm.getMap();
            googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(7.421226f,80.401264f))
            .title("Hello world"));

LogCat

12-31 16:51:54.667: E/AndroidRuntime(10191): FATAL EXCEPTION: main
12-31 16:51:54.667: E/AndroidRuntime(10191): java.lang.NullPointerException
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.adapter.ViewPageAdapter.instantiateItem(ViewPageAdapter.java:201)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.populate(ViewPager.java:979)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:440)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.TheaterDetailFragment$BackGround.onPostExecute(TheaterDetailFragment.java:148)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.TheaterDetailFragment$BackGround.onPostExecute(TheaterDetailFragment.java:1)

Upvotes: 2

Views: 3539

Answers (6)

Mahendran Candy
Mahendran Candy

Reputation: 1144

  1. First check google map is null or notnull using this method --> If(gMap!=null)
  2. Whether you have to download marker icon form url (or) add marker image to the marker info window directly from url.its possible to get the network main thread exception.
  3. Network main thread exception leads to marker image null so that you may get null pointer exception in google map

Solution:

add the following lines in your onCreate method

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);  

Upvotes: 0

Ed Holloway-George
Ed Holloway-George

Reputation: 5149

EDIT: As other answers have mentioned, getMap() is actually now depreciated.

Therefore the below method is no longer recommended, but may still work.


Firstly ensure you have entered your Maps API key to your AndroidManifest.xml

<meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="api-key-here" />

Then ensure the map is defined correctly in your layout (see example below)

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

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

<fragment
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true" />

 </RelativeLayout>   

Once that is completed, you can then access the map as follows

 android.support.v4.app.FragmentManager mFragmentManager = getSupportFragmentManager();
 final SupportMapFragment mMapFragment = (SupportMapFragment) mFragmentManager.findFragmentById(R.id.mapView);
 googleMap = mMapFragment.getMap();

Upvotes: 0

Eugen Pechanec
Eugen Pechanec

Reputation: 38223

1) The fragment may be null.

Unless the map fragment is defined in layout, there's no way you're gonna be able to find it in onCreate. (If this is the case, let me know, I will update the answer.)

2) The fragment has not loaded map yet.

This is the more likely scenario. You can have an instance of MapFragment but it does not have to have an instance of GoogleMap yet. The newest Google Play services SDK (v6.5.87) provide you with a method MapFragment.getMapAsync(OnMapReadyCallback). The callback will run as soon as the GoogleMap instance is available. Only then you can use it.

Upvotes: 1

Ariel Carbonaro
Ariel Carbonaro

Reputation: 1539

getMap is deprecated, use getMapAsync instead. Your Activity needs to implement OnMapReadyCallback interface, so you can add the markers in onMapReady method.

From documentation:

getMap() This method is deprecated. Use getMapAsync(OnMapReadyCallback) instead. The callback method provides you with a GoogleMap instance guaranteed to be non-null and ready to be used.

Upvotes: 0

Lucky Luke
Lucky Luke

Reputation: 147

Apparently, the problem has to with the map itself and not the marker.

First of all, check which version of google play services you are using as library. If you have something before 6.5 version (released in December 2014) then check out the following code (credits at the google play services samples) in order to ensure you are not having a null map object.

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.mapdemo;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */
public class BasicMapDemoActivity extends FragmentActivity {
    /**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}



The other solution, which I strongly recommend, is to get the latest google play services library (check here). Then you will have to change your code according to this guide from google making use of the getMapAsync() (instead of getMap()) and a callback where you can do anything as long as the map is ready to be used, without any more headaches.

Upvotes: 0

Matt Boyle
Matt Boyle

Reputation: 385

Have you checked the map actually loads? I am guessing the null pointer exception is actually coming from the map, not from putting a marker on it.

This tutorial is a great guide on getting started with google maps (including handling exceptions such as this): http://www.vogella.com/tutorials/AndroidGoogleMaps/article.html

Upvotes: 0

Related Questions