android - Google place API for android 查找城市

标签 android google-places-api

我看过教程(tutorial)在 android 中使用自动完成 TextView 查找城市。我已经完成了指示的所有操作,但现在当我点击 this url

它总是抛出一个异常说:java.net.UnknownHostException: Unable to resolve host "maps.googleapis.com": No address associated with hostname

但是当我通过浏览器访问时,相同的 url 工作正常,我也得到了结果。

这是我使用的代码:

public class PlacesAutoCompleteAdapter extends ArrayAdapter< String > implements Filterable{
 private ArrayList<String> resultList;
 private static final String LOG_TAG = "ExampleApp";

 private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
 private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
 private static final String OUT_JSON = "/json";

 private static final String API_KEY = "I have generated the correct api key also";


public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);

}


@Override
public int getCount() {
    return resultList.size();
}

@Override
public String getItem(int index) {
    return resultList.get(index);
}

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
              FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
             if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
        }
    };
    return filter;
}

private ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?sensor=false&key=" + API_KEY);
    //   sb.append("&components=country:in");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));
      // sb.append("&input=" + input);

       System.out.println("URL ---------------: "+sb.toString());
        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        e.printStackTrace();
       // Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}


糟糕!对不起大家。 我找到了一个愚蠢错误的解决方案。我没有在 list 中定义 INTERNET 权限。

最佳答案

请检查您是否在 list 中添加了 INTERNET 权限。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

关于android - Google place API for android 查找城市,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195382/

相关文章:

android - Android的Gradle规则

android - 如何诊断 Eclipse 中的 "Error executing aapt"错误?

android - Google Play 许可是否需要权限 "android.permission.INTERNET"?

javascript - 如何使谷歌地点自动完成结果显示在输入上方

android - Google Places API 不会通过 Android 中的照片引用返回照片

javascript - 动态输入的 Google Places 自动完成功能

javascript - 使用 Google map 地点库在 map 上显示的标记不超过 20 个

java - 在android中将字符串解析为json

google-maps - 嵌入式 Google map 无法在 WebView 中获取当前位置

Android Studio 3.1 "Run"不编译代码