In my app I use Fragments
to show some location based data. The information of the current location of the user is fetched in my MainActivity
and the Fragment
uses these coordinates to proceed. The question I have is, how I let these two classes work together: as I use it now, the Fragment
tries to access the location data in the MainActivity
as soon as it‘s opened, regardless whether the location was already fetched or not. How can I fetch the location and notify the Fragment
afterwards so it knows that it can proceed with its code and access the coordinates properly? Or is the whole procedure thought wrong and that kind of issue is handled differently?
This is the idea of my MainActivity
:
public class MainActivity extends AppCompatActivity {
public static Double lat;
public static Double lon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showLocation();
}
private void showLocation() {
//Grab Location
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
This is the idea of my Fragment
:
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void start(){
if (MainActivity.lat != null && MainActivity.lon != null) {
lat = MainActivity.lat;
lon = MainActivity.lon;
//proceed with location data
} else {
}
}
}