Home > Back-end >  How to use instance of API from Main Activity in Fragments?
How to use instance of API from Main Activity in Fragments?

Time:06-11

If i create an instance of an API in Main Activity, can i use it in fragments so i don't need to create that instance again? Example:

public class MainActivity extends AppCombatActivity {

CustomApi customApi;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customApi = new CustomApi(this, key);

    }

}

How can i access this customApi instance in fragments created by the MainActivity without creating an instance of this CustomApi again?

CodePudding user response:

Fragment has access to its Activity, so you can do something like this in your Fragement:

CustomApi customApi = ((MainActivity) getActivity()).customApi;
customApi.method1(...);

This is a bit brute force, but is a simple and easy way to do the job. This assumes that your Fragment is only used by a single Activity. If your Fragment is used by multiple activities, you could define an Interface and have all parent activities implement that interface and access the customApi that way.

A cleaner, more Android-approved, more professional approach would be to use a ViewModel. The ViewModel is shared by the Activity and all of its Fragments and you could manage the custom API reference in the ViewModel. For some examples of how to use ViewModel to communicate between Activity and Fragment, you can look here:

https://developer.android.com/guide/fragments/communicate

  • Related