0

I'm trying to add a AutoCompleteTextView that will pull the location via GoogleApiClient. I tried many different options to make that work and I get the following error:

Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference

Please tell me what I'm doing wrong, or suggest how to improve that.

Here is the XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.freightos.priceestimator.MainActivity$ContainerFragment"
android:id="@+id/tabContainer">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:gravity="center">

        <AutoCompleteTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/autocomplete"
            android:drawableLeft="@drawable/location_icon_s"
            android:drawablePadding="5dp"
            android:hint="Type in your Location" />

    </LinearLayout>

</LinearLayout>

And here is the ContainerFragment class:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.google.android.gms.common.api.PendingResult;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

import org.w3c.dom.Text;

/**
 * Created by Leonid on 6/30/2016.
 */
public class ContainerFragment extends Fragment {

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
//    public Button btnCallAPI2;

    public ContainerFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /*** Start Location Parameters   *****/
    private AutoCompleteTextView autocomplete;
    private PlacePicker.IntentBuilder builder;
    private PlacesAutoCompleteAdapter mPlacesAdapter;
    private static final int PLACE_PICKER_FLAG = 1;

    private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
            new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
    protected GoogleApiClient mGoogleApiClient;

    /*** End Location Parameters   *****/

    public static ContainerFragment newInstance(int sectionNumber) {
        ContainerFragment fragment = new ContainerFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.container_main, container, false);

        /***** Start of Location Finder  ****/
        autocomplete = (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete);
        mPlacesAdapter = new PlacesAutoCompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1,mGoogleApiClient, BOUNDS_GREATER_SYDNEY, null);
        autocomplete.setOnItemClickListener(mAutocompleteClickListener);
        autocomplete.setAdapter(mPlacesAdapter);
        /***** End of Location Finder  ****/


        return rootView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PLACE_PICKER_FLAG:
                    Place place = PlacePicker.getPlace(data, this.getActivity());
                    autocomplete.setText(place.getName() + ", " + place.getAddress());
                    break;
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

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

    private AdapterView.OnItemClickListener mAutocompleteClickListener
            = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mPlacesAdapter.getItem(position);
            final String placeId = String.valueOf(item.placeId);
            PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                    .getPlaceById(mGoogleApiClient, placeId);
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
        }
    };
    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
            = new ResultCallback<PlaceBuffer>() {
        @Override
        public void onResult(PlaceBuffer places) {
            if (!places.getStatus().isSuccess()) {
                Log.e("place", "Place query did not complete. Error: " +
                        places.getStatus().toString());
                return;
            }
            // Selecting the first object buffer.
            final Place place = places.get(0);
        }
    };
}
Leonid
  • 31
  • 4

1 Answers1

0

You haven't initialised mGoogleApiClient object. Please do the following:

protected void onCreate(Bundle savedInstanceState){
    .....

    // First we need to check availability of play services
    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();
    }

    ....
}

checkPlayServices method:

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
        return false;
    }
    return true;
}

buildGoogleApiClient method:

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

please check out the following link for complete code: source

whdinata
  • 61
  • 5
  • I added the code above, but now I get the following error: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference May be in fragment class it should use the super.onStart(); Or what I'm missing? Is there any example for the fragment class using GoogleAPIClient Object? – Leonid Jul 15 '16 at 19:05
  • Could you make sure that buildGoogleApiClient() method is called? I'm afraid google play service is not available yet. just in case you haven't done yet, please do install the Google Play services library (revision 15 or higher) for your Android SDK. – whdinata Jul 16 '16 at 15:23