0

As title says, I'm getting following exception, when I start up this app:

java.lang.RuntimeException: Unable to start activity ComponentInfo{MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                                                                       at MainActivity.onCreate(MainActivity.java:24)
                                                                       at android.app.Activity.performCreate(Activity.java:6237)
                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                       at android.os.Looper.loop(Looper.java:148) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

The project was created from android template Google Maps. I have activated API key, and copy & paste it to google_maps_api.xml. In my code below, you will also find that I have also set properties regarding access to the internet, and other necessary configuration, etc. I was searching for the similar answer to this issue, but nothing has solved my problem. In the following content, you will find my code:

Manifest.xml

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

<manifest package="com.rile"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
         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="com.rile.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             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"/>
        <uses-library android:required="true" android:name="com.google.android.gms"/>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.rile;

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

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

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

activity_main.xml

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

    <fragment android:id="@+id/map"
              android:name="com.google.android.gms.maps.SupportMapFragment"
              xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context="com.rile.MainActivity"/>
</LinearLayout>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.rile"
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.google.android.gms:play-services:8.4.0'
}

So, how can I fix this exception, in order to make this project to work?

UPDATE:

I have modified code into:

fragment_map.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          class="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

MainActivity.java

package com.rile;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap map) {
        /*
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        */
        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}
Kapparino
  • 988
  • 11
  • 33
  • In the `onCreate` function, can you log what `mapFragment` is (instanceOf), and what is set as? Edit your question, and add more information, since your NPE is a bit open to root causes (also, when was the last time you updated your Android Studio?) – Bonatti Apr 18 '16 at 18:11
  • `getSupportFragmentManager().findFragmentById(R.id.map)` is returning null. Have you tried other methods of adding a fragment to a layout other than using the `` tag? – OneCricketeer Apr 18 '16 at 18:14
  • @Bonatti I'm using latest verson 2.0 Built on April 5, 2016. I can not log this, because it will throw exception again on that. – Kapparino Apr 18 '16 at 18:21
  • @cricket_007 I haven't searched for other methods, since this is google example, and I would like to know why this simple example does not work? Is the problem maybe duo to emulator ? – Kapparino Apr 18 '16 at 18:22
  • I don't think you've quite followed this sample code I found. [Activity](https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/BasicMapDemoActivity.java#L36) and [Layout](https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/res/layout/basic_demo.xml#L16) – OneCricketeer Apr 18 '16 at 18:28
  • I will try that now and inform you soon! Thanks for your attention. – Kapparino Apr 18 '16 at 18:30
  • @Kapparino To log an information use the following: `Log.v("YOUR IDENTIFIER","The variable "+variable);` – Bonatti Apr 18 '16 at 18:40
  • @cricket_007 Please check the updated code, I'm still getting the same exception, with sample code you provided. Am I missing something in manifest ? – Kapparino Apr 18 '16 at 18:40
  • Not really sure what else to tell you. If you want to rule out an emulator problem, then you could download that Github code I linked to and try to run that project. – OneCricketeer Apr 18 '16 at 18:45
  • @Bonatti That is how I wrote code also, but it will throw anyway exception on that line, and I won't be able to return the variable value. – Kapparino Apr 18 '16 at 18:45
  • @cricket_007 Good idea, I will test that now... – Kapparino Apr 18 '16 at 18:46
  • Actually, if you look back at that layout link, you are missing `class="com.google.android.gms.maps.SupportMapFragment"` in your code. – OneCricketeer Apr 18 '16 at 18:47
  • @cricket_007 Modified that line with android:name to class and still same exception :/ – Kapparino Apr 18 '16 at 18:54
  • So, at the end, the above app would work if I set min SDK in gradle.build to 21 and run it on device. However, in emulator with SDK 23 won't. – Kapparino Apr 18 '16 at 20:17
  • Duplicate. This thread have been answered [here](http://stackoverflow.com/questions/26597161/findfragmentbyid-for-supportmapfragment-returns-null-in-android-studio). – ReyAnthonyRenacia Apr 19 '16 at 03:35

0 Answers0