我是Android新手并开发一个显示附近地方的应用程序。它还具有搜索功能,搜索工作正常。问题是如何在操作栏中将searchView小部件设置为自动完成。
更确切地说:
问题在于此代码通过从google places api获取数据来自动填充用户文本条目以及searchview小部件中的建议。在建议地点的项目选择上,选择不会显示在搜索视图中。
例如,如果一个人输入" Berl"在searchview中,自动完成功能会将Berlin显示为建议。但是当用户从列表中选择柏林时,搜索视图框仍然显示Berl而不是柏林,德国,因为它在建议列表中。我想获取用户选择的字符串并在搜索框中显示它
以下是我的主要活动:
GoogleMap mGoogleMap;
private Marker[] placeMarkers;
private final int MAX_PLACES = 20;
private MarkerOptions[] places;
private LocationManager locMan;
private int userIcon, foodIcon, otherIcon;
private SupportMapFragment mapFragment;
private Marker userMarker;
Button pt;
//GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ac=getSupportActionBar();
ac.show();
ac.setDisplayShowTitleEnabled(true);
ac.setTitle("Near By Mosque");
ac.setDisplayUseLogoEnabled(true);
userIcon = R.drawable.marker_img;
foodIcon = R.drawable.nearby_ic;
if(mGoogleMap==null){
//map not instantiated yet
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
}
if(mGoogleMap != null){
//ok - proceed
}
handleIntent(getIntent());
mGoogleMap.setMapType(mGoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setMyLocationEnabled(true);
placeMarkers = new Marker[MAX_PLACES];
updatePlaces();
}
private void handleIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
else if(Intent.ACTION_VIEW.equals(intent.getAction()))
{
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//searchView.setSearchableInfo(PlaceProvider.DETAILS_URI);
searchView.setIconifiedByDefault(true);
AutoCompleteTextView searchTextView =
(AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
if (searchTextView != null) {
searchTextView.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
searchTextView.setTypeface(Typeface.MONOSPACE);
}
searchView.getClass();
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem query) {
switch(query.getItemId()){
case R.id.abs__list_item:
Log.i("menuitme", query.toString());
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, query);
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
Log.i("new loader", cLoader.toString());
return cLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
Log.i("cursor", c.toString());
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
//mGoogleMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mGoogleMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mGoogleMap.animateCamera(cameraPosition);
}
}
private void updatePlaces(){
//update location
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = null;
lastLoc=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
Log.i("latlng",lastLatLng.toString());
if(userMarker!=null) userMarker.remove();
userMarker = mGoogleMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude()), 15.0f));
String types = "mosque";
try {
types = URLEncoder.encode(types, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=3000&sensor=true" +
"&types=" + types +
"&key=AIzaSyCJv8kyIgi7hStqFN3qR-DXF6YMuQ2M6Y0";
new GetPlaces().execute(placesSearchStr);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
@Override
protected String doInBackground(String... placesURL) {
// TODO Auto-generated method stub
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
Log.i("line", lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
placesClient.getConnectionManager().shutdown();
}
}
Log.i("post", placesBuilder.toString());
return placesBuilder.toString();
}
protected void onPostExecute(String result) {
//parse place data returned from Google Places
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
if(placeMarkers != null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
try {
//parse JSON
JSONObject resultObject = new JSONObject(result);
JSONArray placesArray = resultObject.getJSONArray("results");
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
Log.i("place array", places.toString());
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
JSONObject placeObject = placesArray.getJSONObject(p);
JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
placeLL = new LatLng(
Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
JSONArray types = placeObject.getJSONArray("types");
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
Log.i("placename",placeName);
Log.i("types", types.toString());
if(thisType.contains("mosque")){
currIcon = foodIcon;
break;
}
}
}
catch(JSONException jse){
missingValue=true;
jse.printStackTrace();
}
Log.i("marker", places.toString());
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=mGoogleMap.addMarker(places[p]);
}
}
}
}
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updatePlaces();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "status changed");
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider enabled");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider disabled");
}
@Override
protected void onResume() {
super.onResume();
if(mGoogleMap!=null){
}
}
@Override
protected void onPause() {
super.onPause();
if(mGoogleMap!=null){
locMan.removeUpdates(this);
}
}
}