Java 阅读Google在Android中放置API

Java 阅读Google在Android中放置API,java,android,json,google-places-api,Java,Android,Json,Google Places Api,很抱歉这么长时间,但我在这件事上耽搁了一段时间 我试图从Android应用程序中读取Google Places API,我在Eclipse中编写了类似的代码,并且运行成功,但是当我将其更改为Android时,它会中断: public constructor(double lat, double lng, int maxPrice, double distance) throws Exception { responseBuilder = new StringBuilder();

很抱歉这么长时间,但我在这件事上耽搁了一段时间

我试图从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();
                }
            }
        });
    }
当我尝试访问
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.
这是令人不快的功能:

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());
            }
        }
    }
这是我编写的一个函数,用于检查数组是否已填充,它也会崩溃,因为它调用了
arr
的方法:

 public boolean ispopulated() {
        return (arr.length()>0);
    }
我检查了调用是否过快,数组是否没有时间填充,但我让它等待了10秒,100秒,当代码到达该行时仍然崩溃。最初编写代码时,我使用了
URLConnection
,但当它不起作用时,我改为
HTTPURLConnection
,并阅读了一些其他问题


这是在Android中为JSON响应执行API调用的有效方法吗?我有没有更好的方法?我是Android开发新手,所以我不熟悉它的最佳实践。非常感谢您的帮助。

根据您的代码,我假设您希望在Android应用程序中显示满足过滤器要求的位置

谷歌建议首先使用。如果这不适合您的用例,并且您需要使用,请通过代理服务器这样做。使用代理服务器的主要好处是保护API密钥。此外,您还可以防止将过多数据推送到Android客户端

若您正在寻找用于在服务器上编码的最佳库,请使用


而且,由于您是用Java编写代码的,请使用

这可能会有所帮助:谢谢,这正是我想要的,我不知道为什么以前没有找到这些资源。