首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >读取JSONObejct时Google指示错误

读取JSONObejct时Google指示错误
EN

Stack Overflow用户
提问于 2017-10-21 18:43:42
回答 1查看 1.4K关注 0票数 0

在我的应用程序中,我使用Google Place Picker来获取用户将前往的位置的坐标,并且使用Google的方向,我得到了距离(以公里为单位),但有时我在日志中得到了这个错误,没有得到距离和时间:

代码语言:javascript
运行
复制
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err: org.json.JSONException: Index 0 out of range [0..0)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at org.json.JSONArray.get(JSONArray.java:293)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at org.json.JSONArray.getJSONObject(JSONArray.java:521)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.ddz.assistenteauto.Fragments.TravelFragment$4.onResponse(TravelFragment.java:249)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.ddz.assistenteauto.Fragments.TravelFragment$4.onResponse(TravelFragment.java:236)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at android.os.Looper.loop(Looper.java:148)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7325)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
10-21 20:30:23.326 4920-4920/com.ddz.assistenteauto W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

在这里,我如何用http请求向Google发送请求:

代码语言:javascript
运行
复制
private void getDistanceTime(TravelInfo obj){

    Log.d(TAG, "getDistanceTime()");
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity());

    String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getStartLat() + "," + obj.getStartLng() + "&destination=" + obj.getEndLat() + "," + obj.getEndLng() + "&mode=driving&sensor=false";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    //mTextView.setText("Response is: "+ response.substring(0,500));
                    //Log.i(TAG,"Response is: "+ response);

                    try {
                        JSONObject jsonObject = new JSONObject(response);

                        // routesArray contains ALL routes
                        JSONArray routesArray = jsonObject.getJSONArray("routes");
                        // Grab the first route
                        JSONObject route = routesArray.getJSONObject(0);
                        // Take all legs from the route
                        JSONArray legs = route.getJSONArray("legs");
                        // Grab first leg
                        JSONObject leg = legs.getJSONObject(0);
                        //take travel distance
                        JSONObject distanceObject = leg.getJSONObject("distance");
                        String distance = distanceObject.getString("text");
                        //Take travel duration
                        JSONObject durationObject = leg.getJSONObject("duration");
                        String duration = durationObject.getString("text");

                        //Set distance and duration to the class infoTravel that contain coordinates
                        setDistanceTime(distance, duration);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //mTextView.setText("That didn't work!");
            Log.i(TAG,"That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);

}

有人能帮忙吗?

我能从PlacePicker获得用户位置吗?从现在开始,我用它来获取用户位置:

代码语言:javascript
运行
复制
private void getUserLocation() {

    Log.i(TAG, "getUserLocation()");
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        String stringStartLat, stringStartLng;

                        travelInfo.setStartLat(location.getLatitude());
                        travelInfo.setStartLng(location.getLongitude());
                        stringStartLat = Double.toString(travelInfo.getStartLat());
                        stringStartLng = Double.toString(travelInfo.getStartLng());
                        //Set the TextView in the fragment with start coordinates
                        startLatView.setText(stringStartLat);
                        startLngView.setText(stringStartLng);

                        if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
                            Log.i(TAG, "Dentro if userlocation");
                            getDistanceTime(travelInfo);
                        }
                    }
                }
            });
}

编辑

当我得到JSON错误时,我从Google接收到这个JSON

代码语言:javascript
运行
复制
10-21 20:54:18.965 22814-22814/com.ddz.assistenteauto I/TravelFragment: Response is: {
                                                                           "error_message" : "You have exceeded your daily request quota for this API. We recommend registering for a key at the Google Developers Console: https://console.developers.google.com/apis/credentials?project=_",
                                                                           "routes" : [],
                                                                           "status" : "OVER_QUERY_LIMIT"
                                                                        }

编辑

我将键添加到URL中,但仍然得到错误:

代码语言:javascript
运行
复制
String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getStartLat() + "," + obj.getStartLng() + "&destination=" + obj.getEndLat() + "," + obj.getEndLng() + "&mode=driving&AIza*****************FI";

现在用键编辑2,我得到了这个错误:

代码语言:javascript
运行
复制
10-22 15:24:35.540 27362-27362/com.ddz.assistenteauto I/TravelFragment: Response is: {
                                                                           "error_message" : "Requests to this API must be over SSL. Load the API with \"https://\" instead of \"http://\".",
                                                                           "routes" : [],
                                                                           "status" : "REQUEST_DENIED"

所以我把http改为https..。让我们看看}

EN

回答 1

Stack Overflow用户

发布于 2017-10-21 21:37:59

错误消息非常清楚,并表示您正在超出配额,并且您的Directions请求没有使用API密钥。

请注意,对Google服务的无键访问使用共享配额,即使您不发送太多请求,其他没有API密钥的用户可以发送许多请求并使用公共配额。

为了解决这个问题,您必须在控制台中创建一个项目,激活Directions服务并生成一个API密钥。然后,您可以在请求中应用密钥:

String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getStartLat() + "," + obj.getStartLng() + "&destination=" + obj.getEndLat() + "," + obj.getEndLng() + "&mode=driving&key=YOUR_API_KEY";

您可以安全地删除sensor,它已经过时,不再需要了。

有关详细信息,请参阅说明API文档:

https://developers.google.com/maps/documentation/directions/get-api-key

更新

您还应该在响应中正确地处理状态的可能值。有时您可以获得ZERO_RESULTS、NOT_FOUND或UNKNOWN_ERROR,在本例中,routes元素在响应中不存在或为空,这将导致您在代码中观察到的异常。

代码语言:javascript
运行
复制
try {
    JSONObject jsonObject = new JSONObject(response);

    //Get status first
    String status = jsonObject.getString("status");

    if (status.equals("OK")) {
        // routesArray contains ALL routes
        JSONArray routesArray = jsonObject.getJSONArray("routes");
        // Grab the first route
        JSONObject route = routesArray.getJSONObject(0);
        // Take all legs from the route
        JSONArray legs = route.getJSONArray("legs");
        // Grab first leg
        JSONObject leg = legs.getJSONObject(0);
        //take travel distance
        JSONObject distanceObject = leg.getJSONObject("distance");
        String distance = distanceObject.getString("text");
        //Take travel duration
        JSONObject durationObject = leg.getJSONObject("duration");
        String duration = durationObject.getString("text");
        //Set distance and duration to the class infoTravel that contain coordinates
        setDistanceTime(distance, duration);
    } else if (status.equals("NOT_FOUND")) {
        //TODO: handle not found
    } else if (status.equals("ZERO_RESULTS")) {
        //TODO: handle zero results
    } else if (status.equals("OVER_QUERY_LIMIT")) {
        //TODO: handle over query limit
    }
    .....

} catch (JSONException e) {
    e.printStackTrace();
}

            }

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46866759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档