1

I am developing an app that uses Google Maps.So I try to use this code to show the google map marker from database . but when I try it I face problem as following:

I use Mysql database and php file to store Latitude and Longitude.

Anyone know know the solution?

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    MapFragment mapFragment;
    GoogleMap gMap;
    MarkerOptions markerOptions = new MarkerOptions();
    CameraPosition cameraPosition;
    LatLng center, latLng;
    String title;

    public static final String ID = "id";
    public static final String TITLE = "nama";
    public static final String LAT = "lat";
    public static final String LNG = "lng";

    private String url = "http://wisatademak.dedykuncoro.com/Main/json_wisata";

    String tag_json_obj = "json_obj_req";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


    }

    @Override
    public void onMapReady(GoogleMap map) {
        GoogleMap gMap = map;
        getMarkers();
        // Mengarahkan ke alun-alun Demak
        LatLng center = new LatLng(-6.894796, 110.638413);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();

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

    }
    private void addMarker(LatLng latlng, final String title) {
        markerOptions.position(latlng);
        markerOptions.title(title);
  gMap.addMarker(markerOptions);

        gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker marker) {

                Toast.makeText(getApplicationContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Fungsi get JSON marker
    private void getMarkers() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e("Response: ", response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    String getObject = jObj.getString("wisata");
                    JSONArray jsonArray = new JSONArray(getObject);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        title = jsonObject.getString(TITLE);
                        latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));

                        // Menambah data marker untuk di tampilkan ke google map
                        addMarker(latLng, title);
                    }

                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Error: ", error.getMessage());
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
      //  AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }
}

manifest


 <uses-permission android:name="android.permission.INTERNET" /> <!-- https://stackoverflow.com/a/52382711/2711811 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

 implementation 'com.google.android.gms:play-services:6.5.87'
    implementation 'com.android.volley:volley:1.1.1'

this is my XML

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

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

This is a message of logcat ..


04-12 09:08:06.101 10319-10319/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 10319
    java.lang.NullPointerException
        at com.example.myapplication.MainActivity.getMarkers(MainActivity.java:121)
        at com.example.myapplication.MainActivity.onMapReady(MainActivity.java:60)
        at com.google.android.gms.maps.SupportMapFragment$a$1.a(Unknown Source)
        at com.google.android.gms.maps.internal.m$a.onTransact(Unknown Source)
        at android.os.Binder.transact(Binder.java:361)
        at hr.b(:com.google.android.gms.dynamite_mapsdynamite@18382015@18.3.82 (000700-260264002):14)
        at com.google.android.gms.maps.internal.bc.a(:com.google.android.gms.dynamite_mapsdynamite@18382015@18.3.82 (000700-260264002):4)
        at com.google.maps.api.android.lib6.impl.bl.run(:com.google.android.gms.dynamite_mapsdynamite@18382015@18.3.82 (000700-260264002):4)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
04-12 09:08:08.057 10319-10370/com.example.myapplication E/dalvikvm: Could not find class 'dalvik.system.DelegateLastClassLoader', referenced from method com.google.android.gms.dynamite.DynamiteModule.a

Then I replaced this line

  AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);

replaced by this

   RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

After replacing the above line I got the following error

04-13 02:18:02.586 2368-2368/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 2368
    java.lang.NullPointerException
        at com.example.myapplication.MainActivity.addMarker(MainActivity.java:71)
        at com.example.myapplication.MainActivity.access$000(MainActivity.java:30)
        at com.example.myapplication.MainActivity$2.onResponse(MainActivity.java:102)
        at com.example.myapplication.MainActivity$2.onResponse(MainActivity.java:85)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
  • Try using `getSupportFragmentManager()` instead. –  Apr 12 '20 at 12:20
  • @Andy I use it like that ` SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map);mapFragment.getMapAsync(this);` but now I get other error .. Do you have a different solution? –  Apr 12 '20 at 13:40
  • What is "other error" - the `getSupportFragmentManager` is used since you are using `SupportMapFragment`. –  Apr 12 '20 at 16:23

1 Answers1

0

The NullPointerException error occurs when using incorrect fragment manager which returns null if it cannot find the fragment. Your fragment uses the SupportMapFragment so use the SupportFragmentManager as in the example below.

You likely have additional errors - depending on your how you set up your AndroidManifest.xml as identified below.

Here's a simple example of a map fragment resembling your code and is successful - I've posted all relevant parts - so please review thoroughly. Aside from not using the proper fragment manager you likely will have encountered additional errors involving permissions and map API key as listed in AndroidManifest.xml.

Once you get this far then add your getMarkers() to the onMapReady and keep progressing.

AndroidManifest.xml

[Note the permissions required of a map fragment AND a map API key.]

[Also add the .AppController class as the application class otherwise it won't be instantiated automatically and your getInstance will return null.]

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="<<your package>>">

    <uses-permission android:name="android.permission.INTERNET" /> <!-- https://stackoverflow.com/a/52382711/2711811 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:name=".AppController"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

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

</manifest>

build.gradle(app)

dependencies {
    ...
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
}

activity_main.xml

[ Identical to post ]

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

MainActivity.java

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    GoogleMap gMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


    }

    @Override
    public void onMapReady(GoogleMap map) {
        gMap = map;

        // Mengarahkan ke alun-alun Demak
        LatLng center = new LatLng(-6.894796, 110.638413);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();

        gMap.animateCamera( CameraUpdateFactory.newCameraPosition (cameraPosition));
    }
}

And display:

enter image description here

  • Hi Brother, First, thank you for your response/ I have continued following your instructions, it is work like that but The problem occurs when trying to get data / problem into getMarkers(). –  Apr 12 '20 at 21:07
  • Please update your post with any additional errors you are getting with getMarkers(). –  Apr 12 '20 at 22:00
  • Added a note about updating your AndroidManifest with the AppController class. Added the remainder of your code and it works without issue. Be sure to verify this update. –  Apr 12 '20 at 23:48
  • Hi brother, I have updated my question with all changes and all new errors.I apologize for the late reply due to the time difference –  Apr 13 '20 at 06:27
  • Your problem is in the first line of `onMapReady` - you assign `map` to a local variable which is not the same as your class variable of same name so it is null when accessed in addMarker. Simply remove the `GoogleMap` type declaration that line to use the class variable. So it should read `gMap = map;` I updated my example so it is not misleading (although it worked in the example). –  Apr 13 '20 at 12:39
  • this is my first project, so I have very little experience .. You are the best. Thank you.. now it works. –  Apr 13 '20 at 13:02