2

Being new to Android, I am trying to lay my hands on google Map API for a project. I ma trying to implement AutoComplete for google map. I am constantly getting Status{statusCode=NETWORK_ERROR, resolution=null} no matter what I do.

I refered some SO questions like:

but I am unable to resolve the issue. I am passing mPlaceFilter as null, still status.toString() is returning the same error

    private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i("", "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),mBounds, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(mContext, "Error contacting API:: " + status.toString(),Toast.LENGTH_SHORT).show();
            Log.e("", "Error getting autocomplete prediction API call: " + status.toString());
            autocompletePredictions.release();
            return null;
        }

        Log.i("", "Query completed. Received " + autocompletePredictions.getCount()
                + " predictions.");

        // Copy the results into our own data structure, because we can't hold onto the buffer.
        // AutocompletePrediction objects encapsulate the API response (place ID and description).

        Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
        ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
        while (iterator.hasNext()) {
            AutocompletePrediction prediction = iterator.next();
            // Get the details of this prediction and copy it into a new PlaceAutocomplete object.
            resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getFullText(null)));


        }

        // Release the buffer now that all data has been copied.
        autocompletePredictions.release();

        return resultList;
    }
    Log.e("", "Google API client is not connected for autocomplete query.");
    return null;
}

In logcat, I can see

 06-22 11:11:11.979 1730-24663/? E/AsyncOperation: serviceID=65, operation=GetAutoPredictions

 OperationException[Status{statusCode=NETWORK_ERROR, resolution=null}]
                                                  at aimj.b(:com.google.android.gms:0)
                                                  at aily.a(:com.google.android.gms:39)
                                                  at iyv.run(:com.google.android.gms:14)
                                                  at jck.run(:com.google.android.gms:24)
                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                  at jho.run(:com.google.android.gms:0)
                                                  at java.lang.Thread.run(Thread.java:841)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mapapp2">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name="android.support.multidex.MultiDexApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="My KEy" />
    <!--<meta-data -->
        <!--android:name="com.google.android.maps.v2.API_KEY" -->
        <!--android:value="My KEy" />-->
</application>

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • May be you are using wrong key.Try to generate new key and then try it out. – Andy Developer Jun 22 '17 at 06:20
  • don't forget this tag in manifestfile – Andy Developer Jun 22 '17 at 06:25
  • @Andy : Yep, meta-data is already in place. Regenerated the key as well, but still getting same error – Shashank Vivek Jun 22 '17 at 06:54
  • Are you using google map and add this line for google map then remove it. – Andy Developer Jun 22 '17 at 06:55
  • @AndyDeveloper: I didnt get your point of adding and then removing it later. I added, launched and then commented it again but it didnt work. is this what u asked me to do ? – Shashank Vivek Jun 22 '17 at 07:18
  • Bro for googleMap "com.google.android.maps.v2.API_KEY" we use this but when we use PlacesAPI we add this "com.google.android.geo.API_KEY" so when you are using both Google Map and Google Places API you don't need to add "com.google.android.maps.v2.API_KEY" this. Only add this one "com.google.android.geo.API_KEY" otherwise its not working. – Andy Developer Jun 22 '17 at 07:20
  • Please see my answer this works for in my previous project may be this help you out bro. – Andy Developer Jun 22 '17 at 07:41
  • See this answer described here will resolve your problem. https://stackoverflow.com/questions/31449649/android-google-places-api-getautocompletepredictions-returns-status-places-api/54567092#54567092 – Rahul Kushwaha Feb 07 '19 at 06:20

1 Answers1

0

This is what I done in my previous project and it works fine may be this help you out.

// Add this code in onCreate()
mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, 0 , MainActivity.this)
            .addApi(Places.GEO_DATA_API)
            .build();
mGoogleApiClient.connect();


// AutoCompleteTextView AddOnTextChangeListener.
to_auto_txt.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                 int count) {

                if (search_text.length <= 1) {
                    names = new ArrayList<String>();
                    parse = new paserdata();
                    parse.execute();
                }
          }
    });

Parse Data is Asynctask.

 public class paserdata extends AsyncTask<Void, Integer, Void> {
    @Override
    protected Void doInBackground(Void... params) {

        if (mGoogleApiClient.isConnected()) {
            PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, search_text[0], BOUNDS_INDIA, null);
            AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
            final com.google.android.gms.common.api.Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                System.out.println("Error getting autocomplete prediction API call: " + status.toString());
                autocompletePredictions.release();
                return null;
            }
            System.out.println("Query completed. Received " + autocompletePredictions.getCount() + " predictions.");
            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());

            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                names.add(prediction.getFullText(STYLE_BOLD).toString());
            }
            // Release the buffer.
            autocompletePredictions.release();
        } 
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // adp is ArrayAdapter object which declare globally.
        adp = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_list_item_1, names) {
            @Override
            public View getView(int position, View convertView,
                                ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text = (TextView) view
                        .findViewById(android.R.id.text1);
                text.setTextColor(Color.BLACK);
                return view;
            }
        };
       // AutoCompleteTextView.
       to_auto_txt.setAdapter(adp);
    }
}

And the last don't forget to disconnect mGoogleApiClient.

@Override
public void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

You can also disconnect inside onDestroy() too.

Andy Developer
  • 3,071
  • 1
  • 19
  • 39