简体   繁体   中英

Android Google Map API(v2) Show Current Location getting Unfortunately application has stopped error

I am android beginner, I follow a tutorial and try to show the current location on google map using android. Below are the code :

MainActivity.java

package com.example.android_gps_location_detection;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

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

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity {
GoogleMap map;
LocationManager lm;

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

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapView);
    map = mapFragment.getMap();

    map.setMyLocationEnabled(true);

    LocationListener ll = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {

            Toast.makeText(getApplicationContext(),
                    location.getLatitude() + " " + location.getLongitude(),
                    Toast.LENGTH_LONG).show();

            map.addMarker(new MarkerOptions()
                    .position(
                            new LatLng(location.getLatitude(), location
                                    .getLongitude()))
                    .title("my position")
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

            map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                    location.getLatitude(), location.getLongitude()), 15.0f));

        }
    };
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

}

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

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

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

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

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

    <meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBqwF4D-JhpA32_OL8Bw0dKDqc7Jm0CWHQ"/>

    <uses-library android:name="com.google.android.maps" />

    <activity
        android:name="com.example.android_gps_location_detection.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
 The following two permissions are not required to use
 Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<permission
    android:name="com.ram.mapsv2whereami.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.ram.mapsv2whereami.permission.MAPS_RECEIVE" />

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

</manifest>

I got this error map.setMyLocationEnabled(true); this line got NullPointerException, I suspect the getMap() return null. I did some research and found this some suggest used SupportMapFragment. Google Play Services out of date. Requires 3225100 but found 3158130

Project Build Target is Google API level 18 Platform 4.3 my AVD is Target- google api level 18

The problem is in your XML file activity_main.xml:

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

Instead of android:name, you need to use class like this:

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

EDIT:

Sorry, should be just class:, not android:class.

I also had same problem. In my case, it showed 2 errors :

The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

Failed to load map. Error contacting google servers

I solved this by doing :

  1. Validate your API key. This did not solve my problem.
  2. Make sure the project is imported correctly. Neither does it solve the problem.
  3. My API key was valid and the library is imported correctly, so I downloaded the Google Play services library again.
  4. Clean and rebuild all the projects. Nope.
  5. Remove and install the app (not just reinstall). This solved my problem!

EDIT : However it won't work either because you're running your app in an emulator.

It won't work on the AVD since even the latest AVD doesn't support latest Google Play Services SDK (It is a bug).

I suggest you to downgrade the Google Play Services SDK by downloading older SDKs and copy it into the corresponding folder.

Another, If you create a thread that continually checks if getMap() is not null before initializing the Google Map, it would fix some errors in special cases.

EDIT : By the way, in activity_main.xml ,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

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

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

I have no idea why <?xml version="1.0" encoding="utf-8"?> is at the last line of this xml.

Shouldn't the xml declaration be at the first line of the xml?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM