0

I am not able to detect anything when I click on my phone or emulator for a long time. Also, I am not receiving any errors or Logcat messages. I am currently using Android Studio 3.1.3.

package com.example.gaurangadas.test;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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 MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMapLongClickListener {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 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);
    }

    @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));
    }


    @Override
    public void onMapLongClick(LatLng latLng) {
        Toast.makeText(this, "HELLO", Toast.LENGTH_SHORT).show();
        Log.i("LONG CLICK","DETECTED");
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    Maybe this can help you: https://stackoverflow.com/questions/16097143/google-maps-android-api-v2-detect-long-click-on-map-and-add-marker-not-working – Dinorah Tovar Jul 17 '18 at 14:08

1 Answers1

1
mMap.setOnMapLongClickListener(this);

Put this inside your onMapReady() after mMap = googleMap; This will register your onMapLongClick to the mMap google map.

DakDak
  • 21
  • 4
  • 1
    Maybe better is do it in onMapReady callback? – H.Taras Jul 17 '18 at 14:22
  • Now I am getting the following error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gaurangadas.test/com.example.gaurangadas.test.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapLongClickListener(com.google.android.gms.maps.GoogleMap$OnMapLongClickListener)' on a null object reference" –  Jul 17 '18 at 14:24
  • @H.Taras I agree and we see why :) mMap is not initialized yet. I will edit. – DakDak Jul 17 '18 at 14:30