2

I'm trying to follow the directions to make an app with the Google Maps API. To do this, I'm following the instructions exactly as described here: I already had Android Studio and worked on a couple of very elementary Contact List apps, but for this I got the API key, set up the location and network permissions and set up OpenGL ES v2. I copied the following two sections of code right from the website and pasted it to the activity .xml file and the java class.

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

to the layout XML file and the following to the MainActivity.java file.

package com.example.mapdemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

I run into a problem with the first block of code. Android Studio returns the "android.gms.maps.MapFragment" as an error, by highlighting it red. It also gives me an error for all usages of R... any usage of Ris highlighted in red. I tried importing android.R but didn't work. But I guess one problem at a time.

Any ideas? Thanks!

cesium133
  • 155
  • 3
  • 13
  • Did you add google play services to your dependencies? The R issue should be fixed once the map issue is fixed. – stkent Apr 08 '15 at 03:03
  • I actually hadn't. So I just added this line to my build.gradle: "compile 'com.google.android.gms:play-services:7.0.0'". The MapFragment error disappeared. But I still have the R class error. And that's preventing me from compiling and running the app. – cesium133 Apr 08 '15 at 03:20
  • Have you cleaned and rebuilt since including the dependency? – stkent Apr 08 '15 at 03:27
  • Yep, didn't work. Error persists. – cesium133 Apr 08 '15 at 03:45
  • Are you still importing `android.R`? If so, remove that import statement. – stkent Apr 08 '15 at 10:55
  • I removed it after testing it. I still have the R class error. – cesium133 Apr 08 '15 at 14:41

1 Answers1

0

Edit: I just started a new project and followed the instructions from that link. It worked for me. One thing to note is that I didn't have to change anything in MainActivity.java.

I would recommend starting a new project in Android Studio, select "Blank Activity". Modify AndroidManifest.xml, build.gradle, and activity_main.xml, but leave everything in MainActivity.java as is.

One thing to note is that from the SDK Manager, you need to install:

  • Android Support Repository
  • Android Support Library
  • Google Play Services
  • Google Repository

From my working example:

In build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'

    compile 'com.google.android.gms:play-services-maps:7.0.0'
}

AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<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-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".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>

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

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

</application>

I got it set up with a Fragment within MainActivity.

activity_main.xml (nothing special here):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context=".MainActivity" tools:ignore="MergeRootFrame" />

fragment_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity.java:

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.location.Location;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public static class PlaceholderFragment extends Fragment {

        MapView mMapView;
        private GoogleMap googleMap;
        Location location;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // inflate and return the layout
            View v = inflater.inflate(R.layout.fragment_main, container,
                    false);
            mMapView = (MapView) v.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();
            }
            googleMap = mMapView.getMap();
            googleMap.setMyLocationEnabled(true);

            location = googleMap.getMyLocation();

            if (location != null) {

                // latitude and longitude
                LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());

                //double latitude = 17.385044;
                //double longitude = 78.486671;
                //LatLng lat = new LatLng(latitude,longitude);


                // create marker

                MarkerOptions marker = new MarkerOptions().position(
                        lat).title("Hello Maps");

                // Changing marker icon
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

                // adding marker
                googleMap.addMarker(marker);

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(lat).zoom(12).build();


                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            }

            // Perform any camera updates here
            return v;
        }


        @Override
        public void onResume() {
            super.onResume();
            mMapView.onResume();
        }

        @Override
        public void onPause() {
            super.onPause();
            mMapView.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mMapView.onDestroy();
        }

        @Override
        public void onLowMemory() {
            super.onLowMemory();
            mMapView.onLowMemory();
        }
    }
}

Result:

enter image description here

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • I do have all those installed from the original download. I just checked and updated them. Cleaned and rebuilt the project again. No changes. – cesium133 Apr 08 '15 at 04:50
  • Thanks, I think the problem was in some repeated lines of code. I had to rearrange some import lines in the XML file. No errors anymore. Have to wait to see if the code actually does what it's supposed to, since I don't have the USB cable to test on my phone right now... Virtual Device is asking me to install Google Play Services, which I already have. – cesium133 Apr 08 '15 at 17:40