Я занимаюсь разработкой приложения, которое использует Google Map. Поэтому я пытаюсь использовать этот код для отображения маркера карты Google из базы данных. но когда я пытаюсь это сделать, я сталкиваюсь с проблемой следующим образом:
Я использую Mysql базу данных и php файл для хранения Широты и Долготы.
Кто-нибудь знает, знает решение?
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);
}
}
манифест
<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'
это мой 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);
}
}
}
Это сообщение 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
Затем я заменил эту строку
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
и заменил ее
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
После замены вышеупомянутой строки я получил следующую ошибку
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)