将多个字符串映射到autocompletetextview

时间:2016-07-19 09:55:53

标签: android google-places-api autocompletetextview

我使用Google Place API在autocompletetextview中获取地址建议。我还想将纬度和经度映射到地址,以便当用户选择地址时,我可以获得其相关的纬度和经度。我可以使用HashMap映射2个字符串但是如何映射3个字符串然后在autocompletetextview setOnItemClickListener上检索它们?

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "ExampleApp";

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

    //------------ make your specific key ------------
    private static final String API_KEY = "MY_API_KEY";

    private AutoCompleteTextView autoCompView;


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

        autoCompView = (AutoCompleteTextView) findViewById(R.id.query);

        autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));


        autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String str = adapterView.getItemAtPosition(position).toString();
                System.out.println("Selected:"+str);
            }
        });
    }

    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 + OUT_JSON);
            sb.append("?address=" + URLEncoder.encode(input, "utf8"));
            sb.append("&key=" + API_KEY);

            URL url = new URL(sb.toString());

            System.out.println("URL: "+url);
            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("results");

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {

                String address = predsJsonArray.getJSONObject(i).getString("formatted_address");
                JSONObject jobj = new JSONObject(predsJsonArray.getJSONObject(i).getString("geometry"));
                JSONObject jsonObject = new JSONObject(jobj.getString("location"));
                String lat = jsonObject.getString("lat");
                String lng = jsonObject.getString("lng");

                resultList.add(address);
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

    class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
        private ArrayList<String> resultList;

        public GooglePlacesAutocompleteAdapter(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;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您可以创建一个Object来保存结果并实现Object.toString()

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private static final String LOG_TAG = "ExampleApp";

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

//------------ make your specific key ------------
private static final String API_KEY = "MY_API_KEY";

private AutoCompleteTextView autoCompView;


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

    autoCompView = (AutoCompleteTextView) findViewById(R.id.query);

    autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));


    autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String str = adapterView.getItemAtPosition(position).toString();
            System.out.println("Selected:"+str);

            ResultObject resultObject = (ResultObject)adapterView.getItemAtPosition(position);//casting required
            //Do anything with this object



        }
    });
}



public static ArrayList<ResultObject> autocomplete(String input) {
    ArrayList<ResultObject> resultList = null;


    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + OUT_JSON);
        sb.append("?address=" + URLEncoder.encode(input, "utf8"));
        sb.append("&key=" + API_KEY);

        URL url = new URL(sb.toString());

        System.out.println("URL: "+url);
        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("results");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {

            String address = predsJsonArray.getJSONObject(i).getString("formatted_address");
            JSONObject jobj = new JSONObject(predsJsonArray.getJSONObject(i).getString("geometry"));
            JSONObject jsonObject = new JSONObject(jobj.getString("location"));
            String lat = jsonObject.getString("lat");
            String lng = jsonObject.getString("lng");
            ResultObject resultObject = new ResultObject();
            resultObject.setAddress(address);
            resultObject.setLat(lat);
            resultObject.setLng(lng);


            resultList.add(resultObject);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

class GooglePlacesAutocompleteAdapter extends ArrayAdapter<ResultObject> implements Filterable {
    private ArrayList<ResultObject> resultList;

    public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

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

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

protected class ResultObject{
    String address;
    String lat;
    String lng;

    public ResultObject() {
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLng() {
        return lng;
    }

    public void setLng(String lng) {
        this.lng = lng;
    }

    @Override
    public String toString() {
        return getAddress();
    }
}

}