javaandroidandroid-fragmentsandroid-fragmentactivityandroid-googleapiclient

How to user GoogleAPI Client in Fragments


I can't use Google API Client in Fragment.

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_case_summary, container, false);

        initView(rootView);
        return rootView;

      if(mGoogleApiClient==null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
         }

it shows Error : enter image description here


Solution

  • Just switch the return statement and the google API client initialization:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_case_summary, container, false);
    
        initView(rootView);
    
        if(mGoogleApiClient==null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        return rootView;
    }
    

    The return statement should always be the last line in your methods.