好的,现在我正在尝试使用Name,Lat和Long填充Google地图。这些值通过PHP脚本从数据库传入。这一切都很好,工作正常。但我遇到了一个问题:我在AsyncTask中用标记填充地图。这是我得到错误
07-10 14:47:41.035: E/log_tag(21034): Error Parsing Data java.lang.IllegalStateException: Not on the main thread
这是我得到的唯一错误,并没有指明它的位置。我猜这是因为地图没有填充在主线程上?但我不能在主线程上做网络的东西,所以我无法从AsyncTask中删除它。关于如何解决这个问题的任何想法?感谢
代码:
public class MapActivity extends ActionBarActivity implements LocationListener {
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
MapLocations myTask = new MapLocations();
myTask.execute();
}
private class MapLocations extends AsyncTask<Void, Void, Void> {
String msg = "Done";
ArrayList<Marker> arrayOfMarkers;
// Decode image in background.
@Override
protected Void doInBackground(Void... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"MYPHPSCRIPT");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
// resultView.setText("connected");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
// counter++;
map.addMarker(new MarkerOptions().position(
new LatLng(Double.parseDouble(json.getString("PlaceLat")), Double.parseDouble(json
.getString("PlaceLong")))).title(
json.getString("PlaceTitle")));
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
return null;
}
}
}
错误基于此代码 尝试{ JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
// counter++;
map.addMarker(new MarkerOptions().position(
new LatLng(Double.parseDouble(json.getString("PlaceLat")), Double.parseDouble(json
.getString("PlaceLong")))).title(
json.getString("PlaceTitle")));
}
答案 0 :(得分:2)
就在这里
map.addMarker(new MarkerOptions().position(
new LatLng(Double.parseDouble(json.getString("PlaceLat")), Double.parseDouble(json
.getString("PlaceLong")))).title(
json.getString("PlaceTitle")));
由于错误明确指出,您无法在主线程的地图上添加内容。创建一个积分列表然后将其传递给您的onPostExecute
并在那里进行绘图