开始使用谷歌地方自动填充API调用 [英] Getting started with google Place Autocomplete API call
本文介绍了开始使用谷歌地方自动填充API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与谷歌的地方自动完成API调用这样做。我已经看过了从谷歌开发者侧的参考。从那里,我已经提前做了一些code,但我没有得到结果,请帮我找出我的错误...感谢。
这是我的清单。
<清单的xmlns:机器人=http://schemas.android.com/apk/res/android
包=com.example.googleautocompleteapi
安卓版code =1
机器人:=的versionName1.0> <用途-SDK
安卓的minSdkVersion =8
机器人:targetSdkVersion =17/> <使用许可权的android:NAME =android.permission.INTERNET对/>
<使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
<使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAGE/> <应用
机器人:allowBackup =真
机器人:图标=@绘制/ ic_launcher
机器人:标签=@字符串/ APP_NAME
机器人:主题=@风格/ AppTheme>
<活动
机器人:名字=com.example.googleautocompleteapi.MainActivity
机器人:标签=@字符串/ APP_NAME>
&所述;意图滤光器>
<作用机器人:名字=android.intent.action.MAIN/> <类机器人:名字=android.intent.category.LAUNCHER/>
&所述; /意图滤光器>
< /活性GT;
< /用途>< /清单>
这是我的Java文件
公共类MainActivity扩展活动实现OnItemClickListener { 私有静态最后弦乐LOG_TAG =ExampleApp中;
私有静态最后弦乐PLACES_API_BASE =https://maps.googleapis.com/maps/api/place;
私有静态最后弦乐TYPE_AUTOCOMPLETE =/自动完成;
私有静态最后弦乐OUT_JSON =/ JSON; 私有静态最后弦乐API_KEY =AIzaSyD1kYc0zUlKO6i4KfV-ecefi2II6cs4eFM 静态最终HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
静态最终JsonFactory JSON_FACTORY =新JacksonFactory(); @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main); AutoCompleteTextView autoCompView =(AutoCompleteTextView)findViewById(R.id.autocomplete); autoCompView.setText(渔人码头,旧金山,CA,美国);
autoCompView.setAdapter(新PlacesAutoCompleteAdapter(这一点,android.R.layout.simple_dropdown_item_1line));
autoCompView.setOnItemClickListener(本); }
公共无效onItemClick(适配器视图<>适配器视图,视图观点,INT位置,长的id){
字符串str =(字符串)adapterView.getItemAtPosition(位置);
Toast.makeText(这一点,STR,Toast.LENGTH_SHORT).show();
}
@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
} 公共静态的ArrayList<串GT;自动完成(字符串输入){
ArrayList的<串GT; resultList = NULL; HttpURLConnection的康恩= NULL;
StringBuilder的jsonResults =新的StringBuilder();
尝试{
StringBuilder的SB =新的StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append(传感器=假放大器;关键=+ API_KEY);
sb.append(与&组件=国家:英国);
sb.append(&安培;输入=+ URLEn coder.en code(输入UTF8)); 网址URL =新的URL(sb.toString());
康恩=(HttpURLConnection类)url.openConnection();
InputStreamReader的在=新的InputStreamReader(conn.getInputStream()); //将成果转化为一个StringBuilder
INT读;
的char [] = BUFF新的char [1024];
而((读= in.read(BUFF))!= -1){
jsonResults.append(BUFF,0,读);
}
}赶上(MalformedURLException的E){
Log.e(LOG_TAG,错误处理宿API URL,E);
返回resultList;
}赶上(IOException异常五){
Log.e(LOG_TAG,错误连接到Places API的E);
返回resultList;
} {最后
如果(参数conn!= NULL){
conn.disconnect();
}
} 尝试{
//创建一个从结果的JSON对象层次
JSONObject的jsonObj =新的JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray(predictions); //从提取的结果将说明
resultList =新的ArrayList<串GT;(predsJsonArray.length());
的for(int i = 0; I< predsJsonArray.length();我++){
resultList.add(predsJsonArray.getJSONObject(I).getString(说明));
}
}赶上(JSONException E){
Log.e(LOG_TAG,无法处理JSON结果,E);
} 返回resultList;
} 公共类PlacesAutoCompleteAdapter扩展ArrayAdapter<串GT;实现可筛选{
私人的ArrayList<串GT; resultList; 公共PlacesAutoCompleteAdapter(上下文的背景下,诠释textViewResourceId){
超(背景下,textViewResourceId);
} @覆盖
公众诠释的getCount(){
返回resultList.size();
} @覆盖
公共字符串的getItem(INT指数){
返回resultList.get(索引);
} @覆盖
公共过滤用getFilter(){
过滤器过滤器=新的过滤器(){
@覆盖
保护FilterResults performFiltering(CharSequence的约束){
FilterResults filterResults =新FilterResults();
如果(约束!= NULL){
//检索自动完成结果。
resultList =自动完成(constraint.toString()); //分配数据到FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
返回filterResults;
} @覆盖
保护无效publishResults(CharSequence的约束,FilterResults结果){
如果(结果= NULL&放大器;!&安培; results.count大于0){
notifyDataSetChanged();
}
其他{
notifyDataSetInvalidated();
}
}};
返回过滤器;
} }
}
解决方案
我给答案,以我自己的问题......我已经解决了..见下文
公共类MainActivity扩展活动实现OnItemClickListener { @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
AutoCompleteTextView地方=(AutoCompleteTextView)findViewById(R.id.autocomplete);
places.setAdapter(新PlacesAutoCompleteAdapter(这一点,android.R.layout.simple_dropdown_item_1line));
places.setOnItemClickListener(本);
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
} @覆盖
公共无效onItemClick(适配器视图<>适配器视图,视图观点,INT位置,长的id){
// TODO自动生成方法存根
字符串str =(字符串)adapterView.getItemAtPosition(位置);
Toast.makeText(这一点,STR,Toast.LENGTH_SHORT).show();
}}
Adapter类
公共类PlacesAutoCompleteAdapter扩展ArrayAdapter<串GT;实现可筛选{
私人的ArrayList<串GT; resultList; 私有静态最后弦乐LOG_TAG =Places_api; 私有静态最后弦乐PLACES_API_BASE =https://maps.googleapis.com/maps/api/place;
私有静态最后弦乐TYPE_AUTOCOMPLETE =/自动完成;
私有静态最后弦乐OUT_JSON =/ JSON; 私有静态最后弦乐API_KEY =-----;
私人的ArrayList<串GT;自动完成(字符串输入){
ArrayList的<串GT; resultList = NULL; HttpURLConnection的康恩= NULL;
StringBuilder的jsonResults =新的StringBuilder();
尝试{
StringBuilder的SB =新的StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append(传感器=假放大器;关键=+ API_KEY);
sb.append(与&组件=国家:);
sb.append(&安培;输入=+ URLEn coder.en code(输入UTF8)); 网址URL =新的URL(sb.toString());
康恩=(HttpURLConnection类)url.openConnection();
InputStreamReader的在=新的InputStreamReader(conn.getInputStream());
Log.d(====,送Requesst);
//将成果转化为一个StringBuilder
INT读;
的char [] = BUFF新的char [1024];
而((读= in.read(BUFF))!= -1){
jsonResults.append(BUFF,0,读);
}
}赶上(MalformedURLException的E){
Log.e(LOG_TAG,错误处理宿API URL,E);
返回resultList;
}赶上(IOException异常五){
Log.e(LOG_TAG,错误连接到Places API的E);
返回resultList;
} {最后
如果(参数conn!= NULL){
conn.disconnect();
}
} 尝试{
//创建一个从结果的JSON对象层次
Log.d(JSON,解析产生的JSON :));
JSONObject的jsonObj =新的JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray(predictions); //从提取的结果将说明
resultList =新的ArrayList<串GT;(predsJsonArray.length());
Log.d(JSON,predsJsonArray具有长度+ predsJsonArray.length());
的for(int i = 0; I< predsJsonArray.length();我++){ resultList.add(predsJsonArray.getJSONObject(I).getString(说明));
Log.d(JSON,resultList.get(I));
}
}赶上(JSONException E){
Log.e(LOG_TAG,无法处理JSON结果,E);
} 返回resultList;
}
公共PlacesAutoCompleteAdapter(上下文的背景下,诠释textViewResourceId){
超(背景下,textViewResourceId);
} @覆盖
公众诠释的getCount(){
返回resultList.size();
} @覆盖
公共字符串的getItem(INT指数){
返回resultList.get(索引);
} @覆盖
公共过滤用getFilter(){
过滤器过滤器=新的过滤器(){
保护FilterResults performFiltering(CharSequence的约束){
FilterResults filterResults =新FilterResults();
如果(约束!= NULL){
//检索自动完成结果。
resultList =自动完成(constraint.toString()); //分配数据到FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
返回filterResults;
} @覆盖
保护无效publishResults(CharSequence的约束,FilterResults结果){
如果(结果= NULL&放大器;!&安培; results.count大于0){
notifyDataSetChanged();
}
其他{
notifyDataSetInvalidated();
}
} 公共布尔onLoadClass(类为arg0){
// TODO自动生成方法存根
返回false;
}};
返回过滤器;
}
}
I am doing with Google place Auto complete API call. I have looked out the reference from google developer side. From there i have done some code but i am not getting result so please help me for finding out my mistake... Thanks in advance.
This my Manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googleautocompleteapi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.googleautocompleteapi.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is my java file
public class MainActivity extends Activity implements OnItemClickListener{
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 = "AIzaSyD1kYc0zUlKO6i4KfV-ecefi2II6cs4eFM";
static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
autoCompView.setText("Fisherman's Wharf, San Francisco, CA, United States");
autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line));
autoCompView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static 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:uk");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
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) {
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;
}
public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable{
private ArrayList<String> resultList;
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;
}
}
}
解决方案
I am giving answer to to my own question...as i have solved.. see below
public class MainActivity extends Activity implements OnItemClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView places = (AutoCompleteTextView) findViewById(R.id.autocomplete);
places.setAdapter(new PlacesAutoCompleteAdapter(this,android.R.layout.simple_dropdown_item_1line ));
places.setOnItemClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// TODO Auto-generated method stub
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}
Adapter class
public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
private static final String LOG_TAG = "Places_api";
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 = "-----";
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"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
Log.d("====", "Requesst send");
// 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) {
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
Log.d("JSON","Parsing resultant JSON :)");
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
Log.d("JSON","predsJsonArray has length " + predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
Log.d("JSON",resultList.get(i));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
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() {
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();
}
}
public boolean onLoadClass(Class arg0) {
// TODO Auto-generated method stub
return false;
}};
return filter;
}
}
这篇关于开始使用谷歌地方自动填充API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文