Java google places AutoComplete没有显示任何结果
我试图建立一个自动完成从谷歌的地方 在调试器中,我看到返回结果,JSON解析器返回一个位置列表 但是Java google places AutoComplete没有显示任何结果,java,android,json,autocomplete,google-places-api,Java,Android,Json,Autocomplete,Google Places Api,我试图建立一个自动完成从谷歌的地方 在调试器中,我看到返回结果,JSON解析器返回一个位置列表 但是自动完成列表并不在应用程序中 有什么建议吗 代码附在下面 package autocompleat; import android.R.id; import android.view.MotionEvent; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import ja
自动完成
列表并不在应用程序中
有什么建议吗
代码附在下面
package autocompleat;
import android.R.id;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.view.View;
import com.example.hellogooglemaps.MainActivity;
import com.example.hellogooglemaps.R;
import com.google.android.gms.maps.model.LatLng;
import dialogs.JumpToDialog;
public class Autocomplet extends Activity{
AutoCompleteTextView atvPlaces;
PlacesTask placesTask;
ParserTask parserTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jumpto);
JumpToDialog jumpTo = new JumpToDialog();
jumpTo.getActivity();
atvPlaces= (AutoCompleteTextView) findViewById(R.id.addressToGo);
atvPlaces.setThreshold(2);
atvPlaces.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
atvPlaces.showDropDown();
return false;
}
});
atvPlaces.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
placesTask = new PlacesTask();
placesTask.execute(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
private class PlacesTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC5RuWhqvF4SKLzU3J7edVA07Jqon1qEco";
String input = "";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
String contry= "components=country:isr";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&"+ contry+"&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
+ output + "?" + parameters;
try {
// Fetching the data from we service
data = downloadUrl(url);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Creating ParserTask
parserTask = new ParserTask();
// Starting Parsing the JSON string returned by Web Service
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
@Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
// Getting the parsed data as a List construct
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] { "description" };
int[] to = new int[] { android.R.id.text1 };
// Creating a SimpleAdapter for the AutoCompleteTextView
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result,
android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
atvPlaces.setAdapter(adapter);
}
}
public void jumpHandler(final View view)
{
Intent eintent = new Intent();
eintent.putExtra("return",R.id.addressToGo);
setResult(RESULT_OK,eintent);
finish();
}
}
package autocompleat;
import java.util.ArrayList;
import java.util.HashMap;
import com.example.hellogooglemaps.R;
import android.R.string;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;
/** Customizing AutoCompleteTextView to return Place Description
* corresponding to the selected item
*/
public class CustomAutoCompleteTextView extends AutoCompleteTextView {
public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/** Returns the place description corresponding to the selected item */
@Override
protected CharSequence convertSelectionToString(Object selectedItem) {
/** Each item in the autocompetetextview suggestion list is a hashmap object */
HashMap<String, String> hm = (HashMap<String, String>) selectedItem;
return hm.get("description");
}
}
包自动完成;
导入android.R.id;
导入android.view.MotionEvent;
导入android.view.view.OnClickListener;
导入android.view.view.OnTouchListener;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.HashMap;
导入java.util.List;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.content.Intent;
导入android.location.Address;
导入android.location.Geocoder;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.text.Editable;
导入android.text.TextWatcher;
导入android.util.Log;
导入android.widget.AutoCompleteTextView;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.simpledapter;
导入android.view.view;
导入com.example.hellogoglemaps.main活动;
导入com.example.hellogoglemaps.R;
导入com.google.android.gms.maps.model.LatLng;
导入dialogs.JumpToDialog;
公共类自动完成扩展活动{
自动完成文本视图;
PlacesTask PlacesTask;
ParserTask ParserTask;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.jumpto);
JumpToDialog jumpTo=新建JumpToDialog();
跳转到.getActivity();
atvPlaces=(AutoCompleteTextView)findViewById(R.id.addressToGo);
atvPlaces.设置阈值(2);
atvPlaces.setOnTouchListener(新视图.OnTouchListener(){
@凌驾
公共布尔onTouch(视图v,运动事件){
//TODO自动生成的方法存根
atvPlaces.showDropDown();
返回false;
}
});
addTextChangedListener(新的TextWatcher(){
public void onTextChanged(字符序列、int start、int before、int count){
placesTask=新的placesTask();
execute(s.toString());
}
@凌驾
更改前的公共无效(字符序列、整数开始、整数计数、,
整数后){
//TODO自动生成的方法存根
}
@凌驾
公共无效后文本已更改(可编辑){
//TODO自动生成的方法存根
}
});
}
私有类PlacesTask扩展异步任务{
@凌驾
受保护的字符串背景(字符串…位置){
//用于存储来自web服务的数据
字符串数据=”;
//从中获取浏览器密钥https://code.google.com/apis/console
String key=“key=AIzaSyC5RuWhqvF4SKLzU3J7edVA07Jqon1qEco”;
字符串输入=”;
试一试{
input=“input=“+URLEncoder.encode(位置[0],“utf-8”);
}捕获(不支持DencodingException e1){
e1.printStackTrace();
}
//要搜索的位置类型
String types=“types=geocode”;
//传感器启用
字符串sensor=“sensor=false”;
String contry=“components=country:isr”;
//为web服务构建参数
字符串参数=输入+“&”+类型+“&”+传感器+“&”+控制+“&”+键;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/place/autocomplete/"
+输出+“?”+参数;
试一试{
//从we服务获取数据
数据=下载url(url);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(
峡流);
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
urlConnection.disconnect();
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
//创建ParserTask
parserTask=新的parserTask();
//开始解析Web服务返回的JSON字符串
执行(结果);
}
}
/**以JSON格式解析GooglePlaces的类*/
私有类ParserTask扩展
异步任务{
JSONObject jObject;
@凌驾
受保护列表背景(
字符串…jsonData){
列表位置=空;
PlaceJSONParser PlaceJSONParser=new PlaceJ
package autocompleat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("predictions");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String id="";
String reference="";
String description="";
try {
description = jPlace.getString("description");
id = jPlace.getString("id");
reference = jPlace.getString("reference");
place.put("description", description);
place.put("_id",id);
place.put("reference",reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">"
<TextView
android:id="@+id/jumpToTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="right"
android:text="קפוץ לכתובת"
android:textSize="25dp"
android:textColor="#FFFFFF" />
<TextView
android:id="@+id/enterAddressTitle"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:text="הכנס כתובת"
android:textColor="#FFFFFF"
android:textSize="15dp" />
<autocompleat.CustomAutoCompleteTextView
android:id="@+id/addressToGo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/str_atv_places"
android:ems="10"
android:textColor="#000000"
android:textSize="15sp" />
<Button
android:id="@+id/jump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="המשך" />
<Button
android:id="@+id/exitJumpTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="צא" />
</LinearLayout>
atvPlaces.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
atvPlaces.setAdapter(new PlacesAutoCompleteAdapter(context,
R.layout.adapter_list_item));
}
});
private ArrayList<String> autocomplete(String place) {
ArrayList<String> resultList = null;
final String LOG_TAG = "Activity_Home";
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
String key = "key=your key";
// place to be be searched
String input = "input=" + place.replace(" ", "+");
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url_string = "https://maps.googleapis.com/maps/api/place/autocomplete/"
+ output + "?" + parameters;
URL url = new URL(url_string);
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;
}
private 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;
}
}
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv_123"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:textColor="@color/Black"
android:textSize="@dimen/edit_text_text_size_normal" />