我努力從MySQL數據庫接收谷歌地圖標記。 我有這個問題java.lang.NullPointerException:嘗試調用空對象引用上的虛擬方法'int java.util.ArrayList.size()'。我的代碼如何自動實現地圖標記?錯誤的連接或錯誤的代碼?
部分:
ArrayList<HashMap<String, String>> location = null;
try {
JSONArray data = new JSONArray(RetrieveTask.class);
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("lat", c.getString("lat"));
map.put("lng", c.getString("lng"));
location.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < location.size/*here it shows the problem - size*/(); i++) {
String id = location.get(i).get("id");
double lat = Double.parseDouble(location.get(i).get("lat"));
double lng = Double.parseDouble(location.get(i).get("lng"));
LatLng latLng = new LatLng(lat, lng);
MarkerOptions marker = new MarkerOptions().position(latLng).title(id);
googleMap.addMarker(marker);
}
而且從連接到interenet代碼:
private class RetrieveTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String strUrl = "http://12345.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
我不知道什麼是錯我的代碼,我已經嘗試了不同的方式,但仍然得到了同樣的錯誤。 以前有沒有人遇到同樣的問題,你是怎麼理清的?
可能是數據庫故障,因爲它不是遠程的,我使用本地主機? JSON響應正常工作,它返回期望值。
謝謝,只是改變了我的代碼,現在它完美的工作。 –