谷歌地方自动完成没有显示任何结果

时间:2014-04-08 11:00:35

标签: java android json autocomplete google-places-api

我正在尝试从谷歌地方建立一个自动完成 在调试器中,我看到我返回结果,JSON解析器返回一个位置列表

autocomplete列表未在应用中播放

任何建议

代码附在

下面
package autocompleat;

import android.R.id;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.view.View;

import com.example.hellogooglemaps.MainActivity;
import com.example.hellogooglemaps.R;
import com.google.android.gms.maps.model.LatLng;

import dialogs.JumpToDialog;

public class Autocomplet extends Activity{
    AutoCompleteTextView atvPlaces;
    PlacesTask placesTask;
    ParserTask parserTask;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jumpto);
        JumpToDialog jumpTo = new JumpToDialog();   
        jumpTo.getActivity();
    atvPlaces= (AutoCompleteTextView) findViewById(R.id.addressToGo);
    atvPlaces.setThreshold(2);
    atvPlaces.setOnTouchListener(new View.OnTouchListener(){
         @Override
         public boolean onTouch(View v, MotionEvent event) {
             // TODO Auto-generated method stub
              atvPlaces.showDropDown();
             return false;
         }
        }); 
    atvPlaces.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        placesTask = new PlacesTask();
        placesTask.execute(s.toString());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }
});
}
    private class PlacesTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... place) {
            // For storing data from web service
            String data = "";

            // Obtain browser key from https://code.google.com/apis/console
            String key = "key=AIzaSyC5RuWhqvF4SKLzU3J7edVA07Jqon1qEco";

            String input = "";

            try {
                input = "input=" + URLEncoder.encode(place[0], "utf-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            // place type to be searched
            String types = "types=geocode";

            // Sensor enabled
            String sensor = "sensor=false";
            String contry= "components=country:isr";

            // Building the parameters to the web service
            String parameters = input + "&" + types + "&" + sensor + "&"+ contry+"&" + key;

            // Output format
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
                    + output + "?" + parameters;

            try {
                // Fetching the data from we service
                data = downloadUrl(url);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }
        private String downloadUrl(String strUrl) throws IOException {
            String data = "";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        iStream));

                StringBuffer sb = new StringBuffer();

                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                data = sb.toString();

                br.close();

            } catch (Exception e) {
                Log.d("Exception while downloading url", e.toString());
            } finally {
                iStream.close();
                urlConnection.disconnect();
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            // Creating ParserTask
            parserTask = new ParserTask();

            // Starting Parsing the JSON string returned by Web Service
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends
            AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        @Override
        protected List<HashMap<String, String>> doInBackground(
                String... jsonData) {

            List<HashMap<String, String>> places = null;

            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try {
                jObject = new JSONObject(jsonData[0]);

                // Getting the parsed data as a List construct
                places = placeJsonParser.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {

            String[] from = new String[] { "description" };
            int[] to = new int[] { android.R.id.text1 };

            // Creating a SimpleAdapter for the AutoCompleteTextView
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result,
                    android.R.layout.simple_list_item_1, from, to);

            // Setting the adapter
            atvPlaces.setAdapter(adapter);
        }
    }
    public void jumpHandler(final View view)
    {
        Intent eintent = new Intent();
        eintent.putExtra("return",R.id.addressToGo);
        setResult(RESULT_OK,eintent);     
        finish(); 
    }

}

package autocompleat;

import java.util.ArrayList;
import java.util.HashMap;









import com.example.hellogooglemaps.R;

import android.R.string;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;

/** Customizing AutoCompleteTextView to return Place Description
 * corresponding to the selected item
 */
public class CustomAutoCompleteTextView extends AutoCompleteTextView {

    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /** Returns the place description corresponding to the selected item */
    @Override
    protected CharSequence convertSelectionToString(Object selectedItem) {
        /** Each item in the autocompetetextview suggestion list is a hashmap object */
        HashMap<String, String> hm = (HashMap<String, String>) selectedItem;
        return hm.get("description");

    }
}

json解析器

package autocompleat;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {

/** Receives a JSONObject and returns a list */
   public List<HashMap<String,String>> parse(JSONObject jObject){

       JSONArray jPlaces = null;
       try {
           /** Retrieves all the elements in the 'places' array */
           jPlaces = jObject.getJSONArray("predictions");
       } catch (JSONException e) {
           e.printStackTrace();
       }
       /** Invoking getPlaces with the array of json object
        * where each json object represent a place
       */
       return getPlaces(jPlaces);
   }

   private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
       int placesCount = jPlaces.length();
       List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
       HashMap<String, String> place = null;

       /** Taking each place, parses and adds to list object */
       for(int i=0; i<placesCount;i++){
           try {
               /** Call getPlace with place JSON object to parse the place */
               place = getPlace((JSONObject)jPlaces.get(i));
               placesList.add(place);

           } catch (JSONException e) {
               e.printStackTrace();
           }
       }

       return placesList;
   }

   /** Parsing the Place JSON object */
   private HashMap<String, String> getPlace(JSONObject jPlace){

       HashMap<String, String> place = new HashMap<String, String>();

       String id="";
       String reference="";
       String description="";

       try {

           description = jPlace.getString("description");
           id = jPlace.getString("id");
           reference = jPlace.getString("reference");

           place.put("description", description);
           place.put("_id",id);
           place.put("reference",reference);

       } catch (JSONException e) {
           e.printStackTrace();
       }
       return place;
   }
}

layout..xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">"

    <TextView
        android:id="@+id/jumpToTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="right"
        android:text="קפוץ לכתובת"
        android:textSize="25dp" 
        android:textColor="#FFFFFF" />

    <TextView
        android:id="@+id/enterAddressTitle"
        android:layout_width="287dp"
        android:layout_height="wrap_content"
        android:text="הכנס כתובת"
        android:textColor="#FFFFFF"
        android:textSize="15dp" />

    <autocompleat.CustomAutoCompleteTextView
        android:id="@+id/addressToGo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/str_atv_places" 
        android:ems="10"
        android:textColor="#000000"
        android:textSize="15sp" />

    <Button
        android:id="@+id/jump"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="המשך" />

    <Button
        android:id="@+id/exitJumpTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="צא" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

尝试使用此方法

    atvPlaces.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    atvPlaces.setAdapter(new PlacesAutoCompleteAdapter(context,
                            R.layout.adapter_list_item));


                }
            });



private ArrayList<String> autocomplete(String place) {
        ArrayList<String> resultList = null;
        final String LOG_TAG = "Activity_Home";

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            String key = "key=your key";

            // place to be be searched
            String input = "input=" + place.replace(" ", "+");

            // place type to be searched
            String types = "types=geocode";

            // Sensor enabled
            String sensor = "sensor=false";

            // Building the parameters to the web service
            String parameters = input + "&" + types + "&" + sensor + "&" + key;

            // Output format
            String output = "json";

            // Building the url to the web service
            String url_string = "https://maps.googleapis.com/maps/api/place/autocomplete/"
                    + output + "?" + parameters;

            URL url = new URL(url_string);
            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("predictions");

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString(
                        "description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

    private class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
            implements Filterable {
        private ArrayList<String> resultList;

        public PlacesAutoCompleteAdapter(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;
        }
    }

<强> adapter_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_123"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:textColor="@color/Black"
    android:textSize="@dimen/edit_text_text_size_normal" />