Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment setuserVisibleHint true but getActivity returns null

I've been doing some logic inside of a fragment's setUserVisibleHint() method. I was always checking if isVisibleToUser is true and then used getActivity to return the activity. This was working well (100% of the time) until I updated the support library to the latest(support:appcompat-v7:24.2.0). Now getActivity always returns null. Are there some changes to the support library that explain this behaviour?

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(false);

    if (isVisibleToUser) {
      getActivity() <- null
    }
like image 604
noev Avatar asked Sep 16 '16 09:09

noev


2 Answers

I'm a bit late to the party but maybe this can help someone. I solved this problem by creating a boolean member inside the fragment class. I used this then to determine whether or not I was able to successfully get the activity in the setUserVisibleHint method. If not, I execute the activity-related code in onAttach. See below.

public MyFragment extends Fragment {

    ...

    private boolean doInOnAttach = false;

    @Override
    public void setUserVisibleHint(boolean visible) {
        super.setUserVisibleHint(visible);
        // if the fragment is visible
        if (true == visible) {
            // ... but the activity has not yet been initialized
            doInOnAttach = true;
        } else {
            myAction();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (true == doInOnAttach) {
            myAction();
            doInOnAttach = false;
        }
    }

    private void myAction() {
        // code to execute here
    }
}
like image 134
geco17 Avatar answered Nov 15 '22 07:11

geco17


Below Worked for me....

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    //// create class member variable to store view
    viewFrag =inflater.inflate(R.layout.fragment_main_favorite, container, false);

    // Inflate the layout for this fragment
    return viewFrag;
}

and use this

@Override
    public void setUserVisibleHint(boolean visible)
    {
        super.setUserVisibleHint(visible);


            if (visible)
            {

                View v =  viewFrag ;
                if (v == null) {
                    Toast.makeText(getActivity(), "ERROR ", Toast.LENGTH_LONG ).show();
                    return;
                }
            }

    }
like image 31
siddhesh Avatar answered Nov 15 '22 08:11

siddhesh