HTTP请求后,在Google地图上绘制Android Draw Polygone

时间:2017-04-06 20:40:40

标签: android google-maps ui-thread

您好我正在尝试在谷歌地图上绘制多边形后,我从HTTP调用中获取数据。我总是得到同样的错误:

FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.rtuya.secmerev2, PID: 1011                                                                    
java.lang.IllegalStateException: Not on the main thread

以下是我如何进行HTTP调用以及如何尝试绘制区域:

 private void getZones() throws JSONException {
        Request request = new Request.Builder().url(getString(R.string.main_url) + "/api/getZones")
                .headers(buildStandardHeaders(Stormpath.accessToken()))
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override public
            void onFailure(Call call, IOException e) {
                Log.d("DEBUG", "ERROR");
            }
            @Override public void onResponse(Call call, Response response)throws IOException {
                try {
                    JSONArray responseArray = new JSONArray(response.body().string());
                    zones = new ArrayList<ZoneData>();
                    for (int i=0; i < responseArray.length(); i++) {
                        db.addZone(new ZoneData(responseArray.getJSONObject(i)));
                        zones.add(new ZoneData(responseArray.getJSONObject(i)));
                    }
                    isTrackingServiceRunning = startService(new Intent(ActivityMain.this, ServiceTracking.class));
                    bindService(new Intent(ActivityMain.this, ServiceTracking.class), trackerServiceConnection, Context.BIND_AUTO_CREATE);
                    drawAreasOnDashboard();
                } catch (JSONException e) {
                    e.printStackTrace();
                };
            }
        });
    }

下面是我尝试绘制区域的方法,错误总是发生在包含areaMap.drawPolygones()的行上:

public void drawAreas() {
        int polygoneFillingIndex = 1;
        if(ActivityMain.zones != null) {
            for (ZoneData zone : ActivityMain.zones) {
                int color;
                if ((polygoneFillingIndex % 2) == 0) {
                    color = R.color.polygoneFillingBlue;
                } else {
                    color = R.color.polygoneFilingGreen;
                }
                areasMap.addPolygon(new PolygonOptions()
                        .add(zone.getP1(), zone.getP2(), zone.getP3(), zone.getP4())
                        .strokeColor(ResourcesCompat.getColor(getResources(), R.color.polygoneStroke, null))
                        .fillColor(ResourcesCompat.getColor(getResources(), color, null))
                        .zIndex(Float.valueOf(zone.getPosititionInArray()))
                        .clickable(true));

                polygoneFillingIndex++;
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

错误日志确切地说明了你的错误。 Android不允许您在主线程上运行http请求,以免被它阻止。 你必须在AsyncTasks中封装这些http请求,你可以在SO或网络上的任何地方找到大量的例子