使用地点api搜索附近地点时出错

时间:2013-06-30 07:59:37

标签: android google-maps google-places-api

关于使用地点api查找附近地点并尝试将其集成到我的应用程序中,我采取了一项措施。 nearyplaceactivity是runninng但地方结果没有出现。不知道wat是错的,因为代码与教程中提到的几乎相同。以下是我的代码。如果有人能提供帮助,我将非常感激...... tut链接为http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/

package com.example.travelplanner;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class NearbyPlacesActivity extends Activity {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    // Google Places
    GooglePlaces googlePlaces;

    // Places List
    PlacesList nearPlaces;

    // GPS Location
    GPSTracker gps;

    // Button
    Button btnShowOnMap;

    // Progress dialog
    ProgressDialog pDialog;

    // Places Listview
    ListView lv;

    // ListItems data
    ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();


    // KEY Strings
    public static String KEY_REFERENCE = "reference"; // id of the place
    public static String KEY_NAME = "name"; // name of the place
    public static String KEY_VICINITY = "vicinity"; // Place area name

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

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        isInternetPresent = cd.isConnectingToInternet();
        if (!isInternetPresent) {
            // Internet Connection is not present
            alert.showAlertDialog(NearbyPlacesActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // creating GPS Class object
        gps = new GPSTracker(this);

        // check if GPS location can get
        if (gps.canGetLocation()) {
            Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
        } else {
            // Can't get user's current location
            alert.showAlertDialog(NearbyPlacesActivity.this, "GPS Status",
                    "Couldn't get location information. Please enable GPS",
                    false);
            // stop executing code by return
            return;
        }

        // Getting listview
        lv = (ListView) findViewById(R.id.list);

        // button show on map
        btnShowOnMap = (Button) findViewById(R.id.btn_show_map);

        // calling background Async task to load Google Places
        // After getting places from Google all the data is shown in listview
        new LoadPlaces().execute();

        /** Button click event for shown on map */
        btnShowOnMap.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(),
                        PlacesMapActivity.class);
                // Sending user current geo location
                i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
                i.putExtra("user_longitude", Double.toString(gps.getLongitude()));

                // passing near places to map activity
                i.putExtra("near_places", nearPlaces);
                // staring activity
                startActivity(i);
            }
        });


        /**
         * ListItem click event
         * On selecting a listitem SinglePlaceActivity is launched
         * */
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SinglePlaceActivity.class);

                // Sending place refrence id to single place activity
                // place refrence id used to get "Place full details"
                in.putExtra(KEY_REFERENCE, reference);
                startActivity(in);
            }
        });
    }

    /**
     * Background Async Task to Load Google places
     * */
    class LoadPlaces extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NearbyPlacesActivity.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Places JSON
         * */
        protected String doInBackground(String... args) {
            // creating Places class object
            googlePlaces = new GooglePlaces();

            try {
                // Separeate your place types by PIPE symbol "|"
                // If you want all types places make it as null
                // Check list of types supported by google
                // 
                String types = "cafe|restaurant"; // Listing places only cafes, restaurants

                // Radius in meters - increase this value if you don't find any places
                double radius = 1000; // 1000 meters 

                // get nearest places
                nearPlaces = googlePlaces.search(gps.getLatitude(),
                        gps.getLongitude(), radius, types);


            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * and show the data in UI
         * Always use runOnUiThread(new Runnable()) to update UI from background
         * thread, otherwise you will get error
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed Places into LISTVIEW
                     * */
                    // Get json response status
                    String status = nearPlaces.status;

                    // Check for all possible status
                    if(status.equals("OK")){
                        // Successfully got places details
                        if (nearPlaces.results != null) {
                            // loop through each place
                            for (Place p : nearPlaces.results) {
                                HashMap<String, String> map = new HashMap<String, String>();

                                // Place reference won't display in listview - it will be hidden
                                // Place reference is used to get "place full details"
                                map.put(KEY_REFERENCE, p.reference);

                                // Place name
                                map.put(KEY_NAME, p.name);


                                // adding HashMap to ArrayList
                                placesListItems.add(map);
                            }
                            // list adapter
                            ListAdapter adapter = new SimpleAdapter(NearbyPlacesActivity.this, placesListItems,
                                    R.layout.list_item,
                                    new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
                                            R.id.reference, R.id.name });

                            // Adding data into listview
                            lv.setAdapter(adapter);
                        }
                    }
                    else if(status.equals("ZERO_RESULTS")){
                        // Zero results found
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Near Places",
                                "Sorry no places found. Try to change the types of places",
                                false);
                    }
                    else if(status.equals("UNKNOWN_ERROR"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry unknown error occured.",
                                false);
                    }
                    else if(status.equals("OVER_QUERY_LIMIT"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry query limit to google places is reached",
                                false);
                    }
                    else if(status.equals("REQUEST_DENIED"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured. Request is denied",
                                false);
                    }
                    else if(status.equals("INVALID_REQUEST"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured. Invalid Request",
                                false);
                    }
                    else
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured.",
                                false);
                    }
                }
            });

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nearby_places, menu);
        return true;
    }



}

以下logcat仅包含过滤后的错误:

06-30 07:11:42.515: E/AndroidRuntime(743): FATAL EXCEPTION: AsyncTask #1
06-30 07:11:42.515: E/AndroidRuntime(743): java.lang.RuntimeException: An error occured while executing doInBackground()
06-30 07:11:42.515: E/AndroidRuntime(743):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
06-30 07:11:42.515: E/AndroidRuntime(743):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.lang.Thread.run(Thread.java:856)
06-30 07:11:42.515: E/AndroidRuntime(743): Caused by: java.lang.NoClassDefFoundError: com.google.common.base.Preconditions
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.util.ClassInfo.<init>(ClassInfo.java:148)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.util.ClassInfo.of(ClassInfo.java:71)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.util.GenericData.<init>(GenericData.java:58)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.http.HttpHeaders.<init>(HttpHeaders.java:40)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.http.HttpRequest.<init>(HttpRequest.java:72)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.http.HttpTransport.buildRequest(HttpTransport.java:98)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:104)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.google.api.client.http.HttpRequestFactory.buildGetRequest(HttpRequestFactory.java:135)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.example.travelplanner.GooglePlaces.search(GooglePlaces.java:52)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:187)
06-30 07:11:42.515: E/AndroidRuntime(743):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:1)
06-30 07:11:42.515: E/AndroidRuntime(743):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-30 07:11:42.515: E/AndroidRuntime(743):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-30 07:11:42.515: E/AndroidRuntime(743):  ... 4 more
06-30 07:11:56.765: E/WindowManager(743): Activity com.example.travelplanner.NearbyPlacesActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4122bf50 V.E..... R.....ID 0,0-456,144} that was originally added here
06-30 07:11:56.765: E/WindowManager(743): android.view.WindowLeaked: Activity com.example.travelplanner.NearbyPlacesActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4122bf50 V.E..... R.....ID 0,0-456,144} that was originally added here
06-30 07:11:56.765: E/WindowManager(743):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
06-30 07:11:56.765: E/WindowManager(743):   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
06-30 07:11:56.765: E/WindowManager(743):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.Dialog.show(Dialog.java:281)
06-30 07:11:56.765: E/WindowManager(743):   at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.onPreExecute(NearbyPlacesActivity.java:166)
06-30 07:11:56.765: E/WindowManager(743):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
06-30 07:11:56.765: E/WindowManager(743):   at android.os.AsyncTask.execute(AsyncTask.java:534)
06-30 07:11:56.765: E/WindowManager(743):   at com.example.travelplanner.NearbyPlacesActivity.onCreate(NearbyPlacesActivity.java:106)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.Activity.performCreate(Activity.java:5104)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-30 07:11:56.765: E/WindowManager(743):   at android.os.Handler.dispatchMessage(Handler.java:99)
06-30 07:11:56.765: E/WindowManager(743):   at android.os.Looper.loop(Looper.java:137)
06-30 07:11:56.765: E/WindowManager(743):   at android.app.ActivityThread.main(ActivityThread.java:5041)
06-30 07:11:56.765: E/WindowManager(743):   at java.lang.reflect.Method.invokeNative(Native Method)
06-30 07:11:56.765: E/WindowManager(743):   at java.lang.reflect.Method.invoke(Method.java:511)
06-30 07:11:56.765: E/WindowManager(743):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-30 07:11:56.765: E/WindowManager(743):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-30 07:11:56.765: E/WindowManager(743):   at dalvik.system.NativeStart.main(Native Method)

(修订版)将progressdialog放入asynctask

后的Logcat错误
06-30 09:52:03.457: E/Trace(911): error opening trace file: No such file or directory (2)
06-30 09:52:54.746: E/AndroidRuntime(911): FATAL EXCEPTION: AsyncTask #1
06-30 09:52:54.746: E/AndroidRuntime(911): java.lang.RuntimeException: An error occured while executing doInBackground()
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.lang.Thread.run(Thread.java:856)
06-30 09:52:54.746: E/AndroidRuntime(911): Caused by: java.lang.NoClassDefFoundError: com.google.common.base.Preconditions
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.ClassInfo.<init>(ClassInfo.java:148)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.ClassInfo.of(ClassInfo.java:71)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.GenericData.<init>(GenericData.java:58)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpHeaders.<init>(HttpHeaders.java:40)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequest.<init>(HttpRequest.java:72)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpTransport.buildRequest(HttpTransport.java:98)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:104)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequestFactory.buildGetRequest(HttpRequestFactory.java:135)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.GooglePlaces.search(GooglePlaces.java:52)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:186)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:1)
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-30 09:52:54.746: E/AndroidRuntime(911):  ... 4 more

1 个答案:

答案 0 :(得分:0)

您应该在AsyncTask中定义您的对话框而不是活动中的全局变量:

移动:

// Progress dialog
ProgressDialog pDialog;

到您的AsyncTask,请参阅:https://stackoverflow.com/a/6494256/327402