简体   繁体   English

在Android中阅读Google Places API

[英]Reading Google places API in Android

Sorry for the length, but I've been stuck on this for a while. 很抱歉,长度有限,但是我已经坚持了一段时间。

I'm trying to read Google Places API from an Android app, I've written similar code in Eclipse and it runs successfully, however when I changed it for Android it breaks: 我正在尝试从Android应用程序读取Google Places API,我已经在Eclipse中编写了类似的代码并且可以成功运行,但是当我为Android对其进行更改时,它会中断:

public constructor(double lat, double lng, int maxPrice, double distance) throws Exception {
        responseBuilder = new StringBuilder();
        //Format the params
        query = String.format("type=%s&maxprice=%s&opennow=%s&key=%s&location=%s&radius=%s",
                URLEncoder.encode(type,charset),
                URLEncoder.encode(String.valueOf(maxPrice),charset),
                URLEncoder.encode(opennow,charset),
                URLEncoder.encode(apiKey,charset),
                URLEncoder.encode(lat + "," + lng,charset),
                URLEncoder.encode(String.valueOf(distance),charset));
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //Create a connection with the website
                    HttpURLConnection connection = (HttpURLConnection) new URL(url + "?" + query).openConnection();
                    //Set the requrest property
                    connection.setRequestProperty("Accept-Charset", charset);
                    //Get the response
                    InputStream response = connection.getInputStream();
                    //Scan the response
                    Scanner responseScanner = new Scanner(response);
                    while(responseScanner.hasNextLine()) {
                        responseBuilder.append(responseScanner.nextLine());
                    }
                    responseScanner.close();
                    obj = new JSONObject(responseBuilder.toString());
                    //arr is a global variable
                    arr = obj.getJSONArray("results");
                    setRandNumber();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

When I try to access an element (even the first) in arr , 当我尝试访问arr的元素(甚至第一个元素)时,

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
                      at com.example.turtl.project.picker.ispopulated(picker.java:72)
                      at com.example.turtl.project.MainActivity.getRestaurant(MainActivity.java:67)
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:5610) 
                      at android.view.View$PerformClick.run(View.java:22260) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Application terminated.

This is the offending function: 这是令人反感的功能:

public void getResult(View view) throws Exception {
        EditText priceText = (EditText) findViewById(R.id.maxPrice);
        EditText mileText = (EditText) findViewById(R.id.searchSize);
        if (criteriaIsNull(priceText, mileText)) {
            showAlert("Invalid Fields", "Please set a max price and a distance to search");
        } else {
            miles = Integer.parseInt(mileText.getText().toString());
            double meters = milesToMeters(miles);
            maxPrice = Integer.parseInt(priceText.getText().toString());
            if ((miles != previousMiles || maxPrice != previousMaxPrice) && !criteriaIsNull(priceText, mileText)) {
                previousMaxPrice = maxPrice;
                previousMiles = miles;
                picker = new picker(loc.getLatitude(), loc.getLongitude(), maxPrice, meters);
                if (picker.ispopulated()){
                    //This line specifically
                    showAlert(picker.getResultName(), picker.getResultAddress());
                } else {
                    wait(1000);
                }
            } else {
                picker.getNewPlace();
                showAlert(picker.getResultName(), picker.getResultAddress());
            }
        }
    }

This is a function I wrote to check if the array was being populated, it also crashes since it calls a method of arr : 这是我编写的用于检查数组是否正在填充的函数,由于调用了arr方法,它也崩溃了:

 public boolean ispopulated() {
        return (arr.length()>0);
    }

I checked if the call was coming too fast and the array wasn't given time to populate, but I had it wait 10 seconds, and 100 seconds and still the code crashed when it reached that line. 我检查了调用的速度是否太快以及是否没有足够的时间来填充数组,但是我让它等待10秒和100秒,直到到达该行时代码仍然崩溃。 I used URLConnection when I was originally writing the code, but changed to HTTPURLConnection when it didn't work and I read some other questions. 最初编写代码时,我使用了URLConnection ,但当它HTTPURLConnection时,我使用了HTTPURLConnection ,我读了其他一些问题。

Is this a valid way to perform an API call for a JSON response in Android? 这是在Android中为JSON响应执行API调用的有效方法吗? Is there a better way I should be using? 我应该使用更好的方法吗? I'm new to Android development so I'm not familiar with its best practices. 我是Android开发的新手,所以对它的最佳做法不熟悉。 Any help is appreciated. 任何帮助表示赞赏。

From your code, I assume you want to show places in your Android App satisfying a filter. 根据您的代码,我假设您想在Android应用中显示满足过滤条件的位置。

Google recommends to first use Google Places API for Android . Google建议首先使用Android版Google Places API If that doesn't fit your use case, and you need to use Google Places API for Web Service , please do so through a proxy server. 如果这不适合您的用例,并且您需要使用Google Places API for Web Service ,请通过代理服务器使用。 The main benefit of using proxy server is securing your API key. 使用代理服务器的主要好处是保护您的API密钥。 Plus, you can prevent excessive data being pushed to your Android client. 另外,您可以防止将过多的数据推送到您的Android客户端。

If you are looking for best library for coding on server, use Client libraries for Google Maps Web Service . 如果您正在寻找在服务器上进行编码的最佳库,请使用Google Maps Web Service的客户端库

And, since you are coding in Java, use Java client library for Google Maps API Web Services 并且,由于您使用Java进行编码,因此请将Java客户端库用于Google Maps API Web服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM