2

I was trying to run the same code as shown in the following youtube video... Here is the Link

But when I try to run it the map loads but it stops when I search any query(location)... Below is the code:

MainActivity.java

package com.example.maps;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.SearchView;

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;

import java.io.IOException;
import java.util.List;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap gmap;
SupportMapFragment supportMapFragment;
SearchView searchView;


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

    searchView=findViewById(R.id.sv_location);
    supportMapFragment=(SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.pickup);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            String location = searchView.getQuery().toString();
            List<Address> addressList=null;

            if(location != null || !location.equals("")){
                Geocoder geocoder=new Geocoder(MainActivity.this);
                try {
                    addressList=geocoder.getFromLocationName(location,1);

                    Address address = addressList.get(0);
                    LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
                    gmap.addMarker(new MarkerOptions().position(latLng).title(location));
                    gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));

                }catch (IOException e){
                    e.printStackTrace();
                }

            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    supportMapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="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=".MainActivity">

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

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sv_location"
        android:queryHint="Search.."
        android:iconifiedByDefault="false"
        android:layout_margin="10dp"
        android:elevation="5dp"
        android:background="@drawable/bg_round"/>
</RelativeLayout>

I am getting the following error when I search for any location in the SearchView:

I/Choreographer: Skipped 299 frames!  The application may be doing too much work on its main thread.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.maps, PID: 6141
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
        at com.example.maps.MainActivity$1.onQueryTextSubmit(MainActivity.java:50)
        at android.widget.SearchView.onSubmitQuery(SearchView.java:1259)
        at android.widget.SearchView.-wrap8(Unknown Source:0)
        at android.widget.SearchView$5.onEditorAction(SearchView.java:1236)
        at android.widget.TextView.onEditorAction(TextView.java:5911)
        at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
        at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:360)
        at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Tugay
  • 2,057
  • 5
  • 17
  • 32
smith
  • 21
  • 5

2 Answers2

0

You haven't initialized gmap. You can do it like shown in video:

public void onMapReady(GoogleMap googleMap) {
    gmap = googleMap;
}
Tugay
  • 2,057
  • 5
  • 17
  • 32
  • Thanks it worked,,,but now when I search location again and then the marker is created again and again..but I want to remove the marker from last searched location and want to place it to new location..So can you suggest me...? – smith Nov 18 '20 at 14:45
  • I have provided link in the below answer's comment – Tugay Nov 18 '20 at 14:47
  • so should I use gmap.clear() function to remove marker? – smith Nov 18 '20 at 14:55
-1

you are using accessing gmap object without initializing. So initilize it in onMapReady

package com.example.maps;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.SearchView;

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;

import java.io.IOException;
import java.util.List;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap gmap;
SupportMapFragment supportMapFragment;
SearchView searchView;


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

    searchView=findViewById(R.id.sv_location);
    supportMapFragment=(SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.pickup);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            String location = searchView.getQuery().toString();
            List<Address> addressList=null;

            if(location != null || !location.equals("")){
                Geocoder geocoder=new Geocoder(MainActivity.this);
                try {
                    addressList=geocoder.getFromLocationName(location,1);

                    Address address = addressList.get(0);
                    LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
                    gmap.addMarker(new MarkerOptions().position(latLng).title(location));
                    gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));

                }catch (IOException e){
                    e.printStackTrace();
                }

            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    supportMapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
gmap = googleMap;
}

You can clear map by using

gmap.clear();
Wahdat Jan
  • 3,988
  • 3
  • 21
  • 46
  • But now when I search location again and then the marker is created again and again..But I want to remove the marker from last searched location and want to place it to new location..So Can you suggest me...? – smith Nov 18 '20 at 14:42
  • @smith, you have your answer [how to remove marker?](https://stackoverflow.com/a/13692845/11199298) – Tugay Nov 18 '20 at 14:45
  • @WahdatKashmiri, your answer works for clearing but it is not always good practice to use that – Tugay Nov 18 '20 at 14:46
  • @Tuqay Can you suggest me so what else can be a good practice to use in my code? – smith Nov 18 '20 at 14:52
  • @smith it really depends on your use case. If you no longer need and want to remove multiple markers, then the good choice is using `clear()`. But if you want to save some of them, then `remove()` would be a better choice – Tugay Nov 18 '20 at 15:25
  • Okay. Thank you for your clarification, now my doubt is clear...Thanks...! – smith Nov 18 '20 at 16:48