srssdu
srssdu

Reputation: 35

Android: Call fragment functions from Activity, the fragment function contains getActivity() and returns null

I have a fragment as follows:

public class F1 extends Fragment {

    ...
    public void function1 (){
        activity = getActivity();
    }

}

When trying to call this function in the activity which has this fragment,

public class Activity1 extends Activity {

    private F1 f1 = new F1();
    f1.function1();

}

it returns null.

How can I solve this problem? Can anyone provide a working code example?

Upvotes: 0

Views: 147

Answers (1)

Arash GM
Arash GM

Reputation: 10395

It returns null because the fragment didn't attach to the Activity. so use Fragment Manager to access Fragments and also you can use Activity Context in onAttach(Activity activity) , and it would be for sure not Null.

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    this.activityContext = activity; //then use activity context
}

and for getting your Fragment Instance :

F1 f1 = (F1) getFragmentManager().findFragmentByTag(F1.TAG_FRAGMENT);

Upvotes: 1

Related Questions