我正在尝试启动一个新线程,在解析JSON响应并将其存储在hashmap中之后在地图上添加标记。完成此异步任务后,我想通过迭代hashmap值并使用addMarkers()
在地图上添加新标记。当我运行我的应用程序时它崩溃了,我收到了这个错误。
Logcat错误:
at com.google.k.a.cj.b(Unknown Source)
at com.google.maps.api.android.lib6.c.ca.a(Unknown Source)
at com.google.maps.api.android.lib6.c.el.a(Unknown Source)
at com.google.android.gms.maps.internal.l.onTransact(SourceFile:167)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addMarker(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
at com.example.test.testapp.MapsActivity$ParseJSON$1.run(MapsActivity.java:169)
MapsActivity
public class ParseJSON extends AsyncTask<String, Void, Void>
{
@Override
protected Void doInBackground(String... params)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200)
{
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
String noHTML = stripHtml(data);
JSONArray jsonArray = new JSONArray(noHTML);
for(int i = 0; i < jsonArray.length(); i++)
{
NearbyStops stops = new NearbyStops();
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("ID");
stops.name = jsonObject.getString("Name");
stops.lat = jsonObject.getDouble("Lat");
stops.lng = jsonObject.getDouble("Long");
stopHash.put(id, stops);
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
Thread addMarkers = new Thread(new Runnable()
{
@Override
public void run()
{
for(NearbyStops value : stopHash.values())
{
MarkerOptions markerOptions = new MarkerOptions();
String name = value.name;
double lat = value.lat;
double lng = value.lng;
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name);
mMap.addMarker(markerOptions);
}
}
});
addMarkers.start();
}
}
答案 0 :(得分:1)
我怀疑,因为您正在工作线程上访问mMap
Google地图对象。所以,只需删除addMarkers Thread
中的onPostExecute()
,然后直接在onPostExceute()
中添加标记,然后在stopHash
线程中引用一些像addMarker
这样的对象。无法访问(表示您引用的stopHash
中没有值,或者可能是null
)。