getActivity()返回null - 第二次打开片段

时间:2015-11-16 17:29:19

标签: android android-fragments google-maps-api-3

按下按钮时,ShowActivities片段正在实例化。我第一次按下它一切正常。这是我在logCat中得到的:

11-16 23:41:12.560 25874-25874/name.company.newapp E/onCreate: getActivity() == null: false
11-16 23:41:12.560 25874-25874/name.company.newapp E/onCreate: Hash: 1036405628
11-16 23:41:12.570 25874-25874/name.company.newapp E/onCreateView: getActivity() == null: false
11-16 23:41:12.570 25874-25874/name.company.newapp E/onCreateView: Hash: 1036405628
11-16 23:41:12.630 25874-25874/name.company.newapp E/onConnected: getActivity() == null: false
11-16 23:41:12.630 25874-25874/name.company.newapp E/onConnected: Hash: 1036405628

一切都很好。我按后退键并返回上一个片段。现在我再次单击该按钮打开ShowActivities片段,现在logCat返回的是:

11-16 23:41:13.890 25874-25874/name.company.newapp E/onCreate: getActivity() == null: false
11-16 23:41:13.890 25874-25874/name.company.newapp E/onCreate: Hash: 252302789
11-16 23:41:13.890 25874-25874/name.company.newapp E/onCreateView: getActivity() == null: false
11-16 23:41:13.890 25874-25874/name.company.newapp E/onCreateView: Hash: 252302789
11-16 23:41:13.900 25874-25874/name.company.newapp E/onConnected: getActivity() == null: true
11-16 23:41:13.900 25874-25874/name.company.newapp E/onConnected: Hash: 1036405628
虽然onCreate正在创建另一个片段,但在相同的片段上调用

onConnected

ShowActivities片段

    public class ShowActivities extends Fragment implements
            GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {


        public ShowActivities() {
        }

        private static GoogleApiClient googleClient;
        private Location mLastLocation;
        private PendingResult<LocationSettingsResult> result;
        private LocationRequest locationRequest;



        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
         Log.e("onCreate"," "+(getActivity() == null));
            if (googleClient==null) {
                googleClient = new GoogleApiClient.Builder(getActivity())
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .build();
            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
 super.onCreateView(inflater, container, savedInstanceState);
Log.e("onCreateView"," "+(getActivity() == null));
            // Defines the xml file for the fragment
            View view = inflater.inflate(R.layout.upload_activity_fragment, container, false);
            return view;
        }


        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {

        }


        @Override
        public void onConnected(Bundle bundle) {
            Log.e("onConnected"," "+(getActivity() == null));
            locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

            builder.setAlwaysShow(true);
            result = LocationServices.SettingsApi.checkLocationSettings(googleClient, builder.build());

            if (result != null) {
                result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                    @Override
                    public void onResult(LocationSettingsResult locationSettingsResult) {
                        final Status status = locationSettingsResult.getStatus();
                        switch (status.getStatusCode()) {
                            case LocationSettingsStatusCodes.SUCCESS:
                                // All location settings are satisfied. The client can initialize location
                                // requests here.

                                break;
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                // Location settings are not satisfied. But could be fixed by showing the user
                                // a optionsDialog.
                                try {
                                    // Show the optionsDialog by calling startResolutionForResult(),
                                    // and check the result in onActivityResult().
                                    if (status.hasResolution()) {
                                        status.startResolutionForResult(getActivity(), 1000);
                                        Log.e("location", "Resolution");
                                    }
                                } catch (IntentSender.SendIntentException e) {
                                    // Ignore the error.
                                    Log.e("location", "Resolution2");
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                // Location settings are not satisfied. However, we have no way to fix the
                                // settings so we won't show the optionsDialog.
                                break;
                        }
                    }
                });
            }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if ((resultCode == Activity.RESULT_OK) && (requestCode == 1000)) {
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleClient);
            }
        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e("location", "finally");
        }

        @Override
        public void onResume() {
            super.onResume();

        }

        @Override
        public void onPause() {
            super.onPause();
            if (googleClient!=null) {
                googleClient = null;
            }
        }

    }

这已经解决了。一旦我退出片段,我修改了onPause以使googleClient为null。

2 个答案:

答案 0 :(得分:0)

首先尝试通过TAG在占位符中获取Fragment实例,它没有先前的intance,然后创建一个实例。

    Fragment ShowActivities = getFragmentManager().getFragmentByTag(YOUR_TAG);
    if (showActivities == null) {
        showActivities = new ShowActivities();
        getFragmentManager().beginTransaction()
                .replace(R.id.your_placeholder, showActivities, YOUR_TAG)
                .addToBackStack(null)
                .commit();
    }

答案 1 :(得分:0)

首先,请更改onCreateView中的超级方法调用,以便调用super.onCreateView(...)。

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Defines the xml file for the fragment
    View view = inflater.inflate(R.layout.upload_activity_fragment, container, false);
    return view;
}

然后将此片段移至onActivityCreated(...)

client = new NightAssetRestClient(getActivity());
    locationQueries = new LocationQueries(getActivity());
    if (googleClient==null) {
        googleClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

仍然,你需要在onConnect(...)中检查null,因为即使基础Activity被销毁,Async进程也可以保存这个Fragment的引用。

在onCreate方法中添加行setRetainInstance(boolean)可能会有所帮助。