从数据库 android 获取 google 地图数据时出现问题
Problem with Fetch google map data from the database android
我正在开发一个使用 Google Maps.So 的应用程序 我尝试使用此代码显示数据库中的 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" /> <!-- -->
<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.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[=20=]0(MainActivity.java:30)
at com.example.myapplication.MainActivity.onResponse(MainActivity.java:102)
at com.example.myapplication.MainActivity.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)
当使用不正确的片段管理器时会发生 NullPointerException
错误,如果找不到片段,returns null。您的片段使用 SupportMapFragment
因此使用 SupportFragmentManager 如下例所示。
您可能还有其他错误 - 取决于您如何设置 AndroidManifest.xml,如下所示。
这是一个与您的代码相似且成功的地图片段的简单示例 - 我已经 post 编辑了所有相关部分 - 所以请仔细阅读。除了没有使用正确的片段管理器之外,您可能会遇到其他错误,涉及 AndroidManifest.xml.
中列出的权限和映射 API 键
一旦你做到这一点,然后将你的 getMarkers()
添加到 onMapReady
并继续前进。
AndroidManifest.xml
[注意地图片段和地图 API 键所需的权限。]
[同时将 .AppController class 添加为应用程序 class 否则它不会自动实例化并且您的 getInstance
将 return 为空。]
<?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" /> <!-- -->
<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(应用程序)
dependencies {
...
implementation 'com.google.android.gms:play-services-maps:17.0.0'
}
activity_main.xml
[等同于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));
}
}
并显示:
我正在开发一个使用 Google Maps.So 的应用程序 我尝试使用此代码显示数据库中的 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" /> <!-- -->
<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.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[=20=]0(MainActivity.java:30)
at com.example.myapplication.MainActivity.onResponse(MainActivity.java:102)
at com.example.myapplication.MainActivity.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)
当使用不正确的片段管理器时会发生 NullPointerException
错误,如果找不到片段,returns null。您的片段使用 SupportMapFragment
因此使用 SupportFragmentManager 如下例所示。
您可能还有其他错误 - 取决于您如何设置 AndroidManifest.xml,如下所示。
这是一个与您的代码相似且成功的地图片段的简单示例 - 我已经 post 编辑了所有相关部分 - 所以请仔细阅读。除了没有使用正确的片段管理器之外,您可能会遇到其他错误,涉及 AndroidManifest.xml.
中列出的权限和映射 API 键一旦你做到这一点,然后将你的 getMarkers()
添加到 onMapReady
并继续前进。
AndroidManifest.xml
[注意地图片段和地图 API 键所需的权限。]
[同时将 .AppController class 添加为应用程序 class 否则它不会自动实例化并且您的 getInstance
将 return 为空。]
<?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" /> <!-- -->
<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(应用程序)
dependencies {
...
implementation 'com.google.android.gms:play-services-maps:17.0.0'
}
activity_main.xml
[等同于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));
}
}
并显示: