sam sam - 4 months ago 30
Android Question

Map multiple strings to autocompletetextview

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

}

Answer

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

}

Comments