2014-09-21 1 views
1

Je suis assez nouveau pour le développement android, et j'ai fait une application et suivi le long de la documentation du développeur. J'essaie d'intégrer google place api avec la fonctionnalité de saisie semi-automatique dans mon application. Fondamentalement, j'ai intégré mon fragment de carte et mon widget de recherche. Je suis bloqué en essayant d'intégrer le code pour fournir une liste d'endroits chaque fois qu'une lettre est entrée.Comment implémenter la saisie semi-automatique de Google sur un widget de recherche dans mon application Android?

index.java

package com.connortlee.justspace; 

import android.app.Activity; 


import android.app.SearchManager; 
import android.content.Context; 

import android.location.Location; 
import android.location.LocationManager; 
import android.location.LocationListener; 
import android.os.Bundle; 

import android.util.Log; 
import android.view.Menu; 

import android.view.MenuItem; 
import android.view.Window; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.EditText; 
import android.widget.LinearLayout; 

import android.widget.SearchView; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.content.Intent; 
import android.app.Dialog; 
import android.support.v4.app.DialogFragment; 
import android.content.IntentSender; 
import android.widget.TextView.OnEditorActionListener; 
import android.view.KeyEvent; 
import android.view.inputmethod.EditorInfo; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesClient; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 


public class index extends Activity implements LocationListener, 
     GooglePlayServicesClient.ConnectionCallbacks, 
     GooglePlayServicesClient.OnConnectionFailedListener { 
    private GoogleMap googleMap; 
    protected LatLng currentLocation; 
    protected LocationManager locationManager; 
    private LocationClient locationClient; 
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; 


    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.activity_index); 

     SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView searchView = (SearchView) findViewById(R.id.stop); 
     searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 



     //google map and location services 

     googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 
     googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     googleMap.getUiSettings().setZoomControlsEnabled(false); 

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1000, this); 
     } else { 
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 1000, this); 
     } 

    } 

    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     final SearchView stop = (SearchView) findViewById(R.id.stop); 
     if ((keyCode == KeyEvent.KEYCODE_BACK)) { 
      stop.clearFocus(); 
     } 
     return super.onKeyDown(keyCode, event); 
    } 


    private void getLocationClient() { 
     if (locationClient == null) { 
      locationClient = new LocationClient(this, this, this); 
     } 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     setUpMapIfNeeded(); 
     if (servicesConnected()) { 
      getLocationClient(); 
      locationClient.connect(); 
     } 
    } 

    @Override 
    protected void onStop() { 
     locationClient.disconnect(); 
     super.onStop(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     currentLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentLocation, 15); 
     googleMap.animateCamera(cameraUpdate); 
     locationManager.removeUpdates(this); 
    } 


    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 
     Log.d("Latitude", "status"); 
    } 

    public void onProviderEnabled(String provider) { 
     Log.d("Latitude", "enable"); 
    } 

    @Override 
    public void onProviderDisabled(String s) { 
     Log.d("Latitude", "disable"); 
    } 

    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.index, menu); 

     // Get the SearchView and set the searchable configuration 
     SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); 
     searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 

     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    private void setUpMapIfNeeded() { 
     if (googleMap == null) { 
      googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 
     } 
    } 

    /* 
    * Define a request code to send to Google Play services 
    * This code is returned in Activity.onActivityResult 
    */ 

    public boolean servicesConnected() { 
     int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (errorCode != ConnectionResult.SUCCESS) { 
      GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show(); 
      return false; 
     } 
     return true; 
    } 


    /* 
    * Called by Location Services when the request to connect the 
    * client finishes successfully. At this point, you can 
    * request the current location or start periodic updates 
    */ 
    @Override 
    public void onConnected(Bundle dataBundle) { 
     // Display the connection status 
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 

    } 


    /* 
    * Called by Location Services if the connection to the 
    * location client drops because of an error. 
    */ 
    @Override 
    public void onDisconnected() { 
     // Display the connection status 
     Toast.makeText(this, "Disconnected. Please re-connect.", 
       Toast.LENGTH_SHORT).show(); 
    } 


    /* 
    * Called by Location Services if the attempt to 
    * Location Services fails. 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     /* 
     * Google Play services can resolve some errors it detects. 
     * If the error has a resolution, try sending an Intent to 
     * start a Google Play services activity that can resolve 
     * error. 
     */ 
     if (connectionResult.hasResolution()) { 
      try { 
       // Start an Activity that tries to resolve the error 
       connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST); 
       /* 
       * Thrown if Google Play services canceled the original 
       * PendingIntent 
       */ 
      } catch (IntentSender.SendIntentException e) { 
       // Log the error 
       e.printStackTrace(); 
      } 
     } else { 
      /* 
      * If no resolution is available, display a dialog to the 
      * user with the error. 
      */ 
      Toast.makeText(getApplicationContext(), "Sorry. Location services not available.", Toast.LENGTH_LONG).show(); 
     } 
    } 


} 

searchableActivity.java

package com.connortlee.justspace; 

import android.app.ListActivity; 
import android.app.SearchManager; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 


public class SearchableActivity extends ListActivity { 

    private static final String LOG_TAG = "locationAlarm"; 

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

    private static final String API_KEY = "AIzaSyAjtXXyZsECNNewDVAHKiN4QHIEZLWvW3g"; 

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

     // Get the intent, verify the action and get the query 
     Intent intent = getIntent(); 
     if (Intent.ACTION_SEARCH.equals(intent.getAction())) { 

      String query = intent.getStringExtra(SearchManager.QUERY); 
      doMySearch(query); 

     } 
    } 

    private void doMySearch(String query) { 

     Log.d("Event", query); 
    } 


} 

Je suis encore assez nouveau pour le développement android si pointeurs dans la bonne direction serait utile. Merci!

+0

J'essaie toujours de comprendre cela. Je crois que j'ai besoin d'un fournisseur de contenu? – h20poloman

Répondre

1

La bibliothèque de Windwaker est parfaite pour le côté Java. Si vous souhaitez essayer une bibliothèque qui fournit un widget GooglePlaceAutoComplete pour Android, vous pouvez jeter un oeil à Sprockets (je suis le développeur). Une fois la bibliothèque configurée avec votre clé API Google, vous pouvez ajouter un élément GooglePlaceAutoComplete à votre mise en page. Par exemple:

<net.sf.sprockets.widget.GooglePlaceAutoComplete 
    android:id="@+id/place" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 

Et vous pouvez alors obtenir le Place qu'un utilisateur sélectionne en définissant un OnPlaceClickListener.

public void onPlaceClick(AdapterView<?> parent, Prediction place, int position) { 
    /* do something with the Place */ 
} 
0

J'ai créé une bibliothèque en Java pour cela. Il s'agit essentiellement d'un wrapper autour de l'API Google Places et il est complet. Pour utiliser la bibliothèque, vous devez disposer d'une clé API Google Places. (instructions)

Vous pouvez recevoir les prévisions de saisie semi-automatique avec la bibliothèque comme ceci:

GooglePlaces client = new GooglePlaces("YOUR_API_KEY_HERE"); 
List<Place> places = client.getQueryPredictions(query); 

ou par nom de lieu avec:

List<Place> places = client.getPlacePrediction(placeName); 

Assurez-vous de ne pas effectuer ces derniers sur le thread principal !

Library on GitHub

Documentation

Hope this helps!

Questions connexes