首页 > 解决方案 > 尽管实现了 onPause(),但已经管理了一个 id 为 0 错误的 GoogleApiClient

问题描述

单击 Cardview 时,我的应用程序将显示一个启动活动,该活动将在 Recycler 视图中显示附近的地方。但是每当我点击卡片视图时,我都会遇到如下所示的错误。奇迹般地,当我nearByPlace("restaurant")在 NearbyActivity.java 中注释掉时,程序并没有崩溃。是否有可能,因为 nearByPlace("restaurant") 也使用相同的 ID,我该如何解决

java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.android.sunshine/com.example.android.sunshine.MainActivity}:java.lang.IllegalStateException:已经在管理 ID 为 0 的 GoogleApiClient

错误日志猫

ItemOneFragment.Java

private void init() {
        mGeoDataClient = Places.getGeoDataClient(getActivity(), null);
        // Construct a PlaceDetectionClient.
        mPlaceDetectionClient = Places.getPlaceDetectionClient(getActivity(), null);
        mGoogleApiClient = new GoogleApiClient
                .Builder(getActivity())
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .enableAutoManage(getActivity(), 0, this)
                .build();
        SessionData.setSessionId("0");
        mSearchText.setOnItemClickListener(mAutocompleteClickListener);
        placeAutocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(), mGeoDataClient, LAT_LNG_BOUNDS, null);
        mSearchText.setAdapter(placeAutocompleteAdapter);

    }

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        cardShopMall = (CardView) getView().findViewById(R.id.textViewShopMall);
        cardShopMall.setOnClickListener(cardShopMallOnClickListener);


        if (isServicesOK()) {
            getLocationPermission();
        }
        if (mLocationPermissionsGranted) {
            getDeviceLocation();
            init();
        }


    }

CardView.OnClickListener cardShopMallOnClickListener = new CardView.OnClickListener(){
        @Override
        public void onClick(View view) {
            String type = "shopping_mall";
            Intent i = new Intent(getContext(),NearbyActivity.class);
            i.putExtra("type",type);
            i.putExtra("latitude",latitude);
            i.putExtra("longitude",longitude);
            startActivity(i);
        }
    };

NearbyActivity.Java

IGoogleAPIService mServiceNear;
    private GoogleApiClient mGoogleApiClient;

    public NearbyActivity() {
        Retrofit retrofit1 = RetrofitClient2.getClient("https://maps.googleapis.com/");
        mServiceNear = retrofit1.create(IGoogleAPIService.class);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

               mGoogleApiClient = new GoogleApiClient
                        .Builder(this)
                        .addApi(Places.GEO_DATA_API)
                        .addApi(Places.PLACE_DETECTION_API)
                        .enableAutoManage(this, 2 ,this)
                        .build();

        Intent intent = getIntent();
        String type = intent.getExtras().getString("type");
        latitude = intent.getExtras().getDouble("latitude");
        longitude = intent.getExtras().getDouble("longitude");

        try {
            nearByPlace("restaurant");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void nearByPlace(final String type) {
        String url = getUrl(latitude,longitude,type);
        Log.d(TAG,"underURL@ nearByPlace : " + url);

        mServiceNear.getNearByPlaces(url)
                .enqueue(new Callback<MyPlaces>() {
                    @Override
                    public void onResponse(Call<MyPlaces> call, retrofit2.Response<MyPlaces> response) {

                        try {
                            if (response.isSuccessful()){
                                Log.d(TAG,"responnse : ok");

                                try {
                                    if (response.body() != null){
                                        for (int i=0;i<response.body().getResults().length;i++){

                                            Results googlePlace = response.body().getResults()[i];
                                            String placeName = googlePlace.getName();
                                            String vicinity = googlePlace.getVicinity();
                                            Log.d(TAG,"nearByPlaces: " + placeName);
                                            ListItem item = new ListItem(
                                                    googlePlace.getName(),
                                                    googlePlace.getVicinity()
                                            );
                                            listItems.add(item);
                                        }
                                    }else {
                                        Toast.makeText(getApplicationContext(),"No Nearby " + type,Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                adapter = new MyAdapter(listItems,NearbyActivity.this);
                                recyclerView.setAdapter(adapter);
                            }
                        }catch (Exception e){
                            e.getMessage();
                        }

                    }

                    @Override
                    public void onFailure(Call<MyPlaces> call, Throwable t) {

                    }
                });

    }

    private String getUrl(double latitude, double longitude, String restaurant) {
        StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlacesUrl.append("location="+latitude+","+longitude);
        googlePlacesUrl.append("&radius="+5000);
        googlePlacesUrl.append("&type="+restaurant);
        googlePlacesUrl.append("&sensor=true");
        googlePlacesUrl.append("&key="+getResources().getString(R.string.GoogleAPiKey));

        Log.d(TAG,"getURL : " + googlePlacesUrl.toString());
        return googlePlacesUrl.toString();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.stopAutoManage(this);
            mGoogleApiClient.disconnect();
        }
    }

标签: javaandroidandroid-activitygoogle-places-api

解决方案


是的,您已为您的 Activity 正确实施onPause,但没有为您的Fragment.

在您init的 Fragment 方法中,您创建一个新的GoogleApiClient. 这与你的不同Activity,如前所述,你正确地实现了onPause

因此,您的问题的解决方案应该onPause为您的 Fragment 实施。

我希望这能解决你的问题


推荐阅读