自动完成文本视图谷歌地点API

7
我按照这个教程进行编程,使用Google Places API实现自动完成文本视图。我想要一个自动完成文本视图,当我们开始输入时,它会自动填充地点名称。上述提到的教程正是我需要的,但它对我不起作用。自动填充操作没有发生。有人能否提出解决方法?
以下是主要活动。
 public class MainActivity extends Activity {

AutoCompleteTextView atvPlaces;
PlacesTask placesTask;
ParserTask parserTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
    atvPlaces.setThreshold(1);

    atvPlaces.addTextChangedListener(new TextWatcher() {

        @Override
        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
        }
    });
}

/** A method to download json data from url */
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));

        StringBuilder sb = new StringBuilder();

        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;
}

// Fetches all places from GooglePlaces AutoComplete Web Service
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=AIzaSyBB5KBkuA4-qm8QxaXX8FhHqhHsESMdAzI";

        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";

        // 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 = "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;
    }

    @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);
    }
}

@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;
}
}

这是PlaceJSONParser.java文件

 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;
}
}

这是CustomAutoCompleteTextView.java文件

 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");
}
}

这是清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map5"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.map5.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>


如果您按照所述的教程进行操作,那么它应该可以正常工作。如果没有,请提供必要的代码,否则很难猜测您在做什么。 - Joel Fernandes
@JoelFernandes,我不知道出了什么问题。但是我没有得到自动填充的效果。 - jincy abraham
2个回答

7
setThresholdshowDropDown 添加到您的 autocompletetextview 中以显示建议。
 atvPlaces.setOnTouchListener(new View.OnTouchListener(){
   @Override
   public boolean onTouch(View v, MotionEvent event){
      atvPlaces.showDropDown();
      return false;
   }
}); 

请参考此链接:这里

更改了密钥并添加了这段代码。现在它可以工作了。非常感谢:) - jincy abraham
有人能为两个自动完成文本视图建议所需的编辑吗?比如,一个用于源地点,另一个用于目的地。 - jincy abraham
2
兄弟,我是 Android 新手。我也在使用你用过的同一教程,但我的自动填充操作没有发生。我使用了这个链接获取了 Google 浏览器 API 密钥:https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters。非常感谢您提供的任何帮助。提前致谢。 - Muhammad Zahid

1
在开发者控制台中启用Google Places API Web Service

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接