androidgoogle-play-developer-apiactivity-oncreateview

How to get onCreate to load before onCreateView when using getActivity in onCreate?


I have a code that is using GooglePlayAPI to get the location. In that piece of code I am using getAcvitity since this is a fragment and I put it in my OnCreate. Because I want the values displayed in a recyclerview I put that part of my code in onCreateView. Unfortunately the location code is causing my onCreate to load after my onCreateView, thus I have a recyclerview with no values. I tried to put my location code in my onCreateView but that doesnt work. Does anyone know of a solution to my problem? Here is my code.

public class TestFragment extends Fragment {
private double latitude;
private static double longitude;

private FusedLocationProviderClient mFusedLocationClient;


RecyclerView mRecyclerView;
PlanetRecyclerViewAdapter adapter;
private OnFragmentInteractionListener mListener;

public TestFragment() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    requestPermission();

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());

    if (ActivityCompat.checkSelfPermission(getActivity(), ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)  {
        Toast.makeText(getActivity(), "Please provide Location Permission to continue ", Toast.LENGTH_LONG).show();
        return;
    }
    mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {

            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();

                System.out.println("This is latitude:" + latitude);



            }

        }
    });


    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);



    }


}


private void requestPermission(){
    ActivityCompat.requestPermissions(getActivity(),new String[]{ACCESS_FINE_LOCATION}, 1);
}


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

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_test, container, false);



    mRecyclerView = (RecyclerView)view.findViewById(R.id.planet_recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(),DividerItemDecoration.VERTICAL));

    adapter = new PlanetRecyclerViewAdapter(items, mRecyclerView.getContext());
    mRecyclerView.setAdapter(adapter);




    return view;
}




@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}


Solution

  • getLastLocation() is asynchronous code, because of this it is occur after onCreateView. Try to put getLastLocation() inside onCreateView like this:

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    
    // Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.fragment_test, container, false);
    
    
    
    mRecyclerView = (RecyclerView)view.findViewById(R.id.planet_recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(),DividerItemDecoration.VERTICAL));
    
    mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
        @Override 
        public void onSuccess(Location location) { 
    
            if (location != null) { 
                latitude = location.getLatitude(); 
                longitude = location.getLongitude(); 
    
                System.out.println("This is latitude:" + latitude); 
                adapter = new PlanetRecyclerViewAdapter(items, mRecyclerView.getContext());
                mRecyclerView.setAdapter(adapter);
    
    
            } 
    
        } 
    }); 
    
    
    
    
    return view;
    } 
    

    This way only when you receive the location you will set the adapter and attach it to recyclerview. I didn't found in your code where you declare items for adapter.