2016-07-19 6 views
0

Google Place APIを使用して、autocompletetextviewでアドレス候補を取得しています。また、ユーザーが住所を選択したときに関連する緯度と経度を取得できるように、住所と緯度と経度をマッピングする必要があります。私は2つの文字列をマッピングするためにHashMapを使うことができますが、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

あなたは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(); 
    } 
} 

}

+0

おかげで結果を保持し、実装するためのオブジェクトを作成することができます。 Objectクラスを実装しましたが、 'autoCompView.setOnItemClickListener'内の' ResultObject resultObject = adapterView.getItemAtPosition(position); '行に互換性のないエラーが発生しています。エラー:必要なResultObject、見つかったオブジェクト – Sammy

+0

私の悪い、@Overrideを持っています public String getItem(int index){ return resultList.get(index)/ *。toString()* /; }戻り値とオブジェクトおよび文字列ではなく、ResultObjectをキャストすることもできます。resultObject =(ResultObject)adapterView.getItemAtPosition(position); –

+0

'@Overrideを使用するとエラーになります public String getItem(int index){ return resultList.get(index); } ' 私は' @Overrideを使用しました。 public ResultObject getItem(int index){ return resultList.get(index); } '代わりに – Sammy

関連する問題