6
votes

I want to load a Google Maps object and create some listener:

I created this class:

import java.lang.ref.WeakReference;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.Toast;

public class itemSaleActivity extends FragmentActivity  {
    private static Context app;
    private static GoogleMap map;
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    private static final int LOAD_COORD = 0;
    private ImageView pic;
    private LocationHandler mHandler;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Set View to register.xml
        setContentView(R.layout.itemsale);

        app = getApplicationContext();
        Bundle extras = getIntent().getExtras();
        byte[] byteArray = extras.getByteArray("picture");
        Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

        pic = (ImageView) findViewById(R.id.itemImage);
        pic.setImageBitmap(bmp);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        //Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg"));
        mHandler = new LocationHandler(this);

        OnMarkerDragListener markerDragListener = new OnMarkerDragListener() {

            @Override
            public void onMarkerDragStart(Marker marker) {
                // Called when the marker drag is started
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                // Called when the marker is dropped down.
                double[] coords = null;
                coords[0] = marker.getPosition().latitude;
                coords[1] = marker.getPosition().longitude;
                RestoreUIwithSavedLocation(coords);
                Toast.makeText(getApplicationContext(),"Pin Dropped at: " + coords[0] + ", " + coords[1]+marker.getTitle() , Toast.LENGTH_LONG).show();
            }

            @Override
            public void onMarkerDrag(Marker marker) {

            }
        };

        map.setOnMarkerDragListener(markerDragListener);

        View titleView = getWindow().findViewById(android.R.id.title);
        if (titleView != null) {
            ViewParent parent = titleView.getParent();
            if (parent != null && (parent instanceof View)) {
             View parentView = (View)parent;
             parentView.setVisibility(View.GONE);
            }
        }

        // You can also assign the title programmatically by passing a
        // CharSequence or resource id.
    }

    private void RestoreUIwithSavedLocation(double[] coordsArray) {
        Message.obtain(mHandler, LOAD_COORD, coordsArray).sendToTarget();
    }

    static class LocationHandler extends Handler {
        WeakReference<Activity> mActivity;

        public LocationHandler(Activity activity) {
            mActivity = new WeakReference<Activity>(activity);
        }

        public void handleMessage(Message msg) {
            Activity contextActivity = mActivity.get();
            switch ((int)msg.what) {

            case LOAD_COORD:
                map.clear();
                double[] coordArray = (double[])msg.obj;
                Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(coordArray[0], coordArray[1])));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(coordArray[0], coordArray[1]), 18));
                map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
                marker.setDraggable(true);
                String s = Double.toString(coordArray[0]) + ", " + Double.toString(coordArray[1]);
                Toast.makeText(app,"in the case"+s , Toast.LENGTH_LONG).show();
                break;
            }
        }
    }
}

And this is the XML:

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

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

    <ImageView
        android:id="@+id/itemImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/logo" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="400dp"
        android:layout_marginTop="10dp"
        android:layout_weight="66496.79"
        android:orientation="horizontal" >

        <fragment
            android:id="@+id/map"
            class="com.google.android.gms.maps.MapFragment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="150dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="170dp"
            android:orientation="vertical" >

            <Button
            android:id="@+id/messageBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:text="fffff" />

            <Button
                android:id="@+id/call"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:text="ffff" />

        <Button
            android:id="@+id/sms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/button1"
            android:layout_centerVertical="true"
            android:text="ffff" />
        <Button
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/button1"
            android:layout_centerVertical="true"
            android:text="fffff" />

        <Button
            android:id="@+id/navigate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button1"
            android:layout_alignParentEnd="false"
            android:layout_alignParentStart="false"
            android:layout_below="@+id/button1"
            android:layout_marginTop="14dp"
            android:text="ffffffffff" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

And when I debug it on my phone (galaxy s2), it shows me an exception:

03-29 15:24:29.750: E/AndroidRuntime(2579): FATAL EXCEPTION: main
03-29 15:24:29.750: E/AndroidRuntime(2579): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sal/com.example.sal.itemSaleActivity}: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2079)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.access$600(ActivityThread.java:132)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.os.Looper.loop(Looper.java:137)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.main(ActivityThread.java:4575)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at java.lang.reflect.Method.invokeNative(Native Method)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at java.lang.reflect.Method.invoke(Method.java:511)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at dalvik.system.NativeStart.main(Native Method)
03-29 15:24:29.750: E/AndroidRuntime(2579): Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Activity.setContentView(Activity.java:1835)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.example.sal.itemSaleActivity.onCreate(itemSaleActivity.java:45)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Activity.performCreate(Activity.java:4465)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
03-29 15:24:29.750: E/AndroidRuntime(2579):     ... 11 more
03-29 15:24:29.750: E/AndroidRuntime(2579): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.Fragment.instantiate(Fragment.java:388)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.Fragment.instantiate(Fragment.java:363)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:264)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
03-29 15:24:29.750: E/AndroidRuntime(2579):     ... 22 more

where line 26 in the xml file is:

  <fragment
                android:id="@+id/map"
                class="com.google.android.gms.maps.MapFragment"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginRight="150dp" />
3
try using, class="com.google.android.gms.maps.SupportMapFragment". - Amol Sawant 96 Kuli
i tried it and now it show me a nullPointerException at line: map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); - Adir Rahamim
here is a good tutorial of implementing GoogleMapV2 step by step. Hope this will helps you. - Amol Sawant 96 Kuli
The difficulty of getting Google Maps on Android working is astounding. If anyone wants to know how bad Android is as a development environment I point to Maps. - Cameron Lowell Palmer

3 Answers

10
votes

In the XML file, use class="com.google.android.gms.maps.SupportMapFragment".

In you main class, use:

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

Instead of:

map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
2
votes

To add SupportMapFragment to your project you need to add google-support-v4 library and google map libraries. You can read about how to do that in a blog post I wrote, Google Maps API V2.

1
votes

FragmentActivity is provided by the Android Support Library v4 to allow Android platforms before Android 3 (Honeycomb) to use fragments. With Honeycomb and later, fragments are supported using by the standard Activity class

The catch is, depending on the activity class you choose, you cannot use the same fragment class:

  • with android.support.v4.app.FragmentActivity, you muse use android.support.v4.app.Fragment
  • with android.app.Activity, you must use android.app.Fragment

Note the package difference.

Now, with respect to Google Maps v2 for Android, you have two Fragment implementations:

  • MapFragment which extends android.app.Fragment for Honeycomb and later
  • SupportMapFragment which extends android.support.v4.app.Fragment for support of the older Android versions

So, as you use FragmentActivity, you must use the SupportMapFragment implementation for your application.