将多个字符串映射到autocompletetextview(Map multiple strings to autocompletetextview)

编程入门 行业动态 更新时间:2024-10-28 03:18:14
多个字符串映射到autocompletetextview(Map multiple strings to 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; } } }

I'm using Google Place API to get address suggestion in autocompletetextview. I also want to map latitude and longitude with the address so that when user selects an address I can get its related latitude and longitude. I can use HashMap for mapping 2 strings but how to map 3 strings and then retrieve them on 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; } } }

最满意答案

您可以创建一个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(); } }

}

You can create a Object to hold the results and implement an 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(); } }

}

更多推荐

本文发布于:2023-08-02 15:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字符串   autocompletetextview   strings   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!