Search code examples
javaandroidandroid-fragmentsnullpointerexceptionfindviewbyid

How to correctly retrieve view from fragment in main activity


is there a specific way or a specific moment in which I can retrieve in my MainActivity a view from a Fragment, being sure that the element is already initialized?

I of course used the findViewById() method in my MainActivity but it returns null if the Fragment is not already initialized, so I've tried to call an initializing method of MainActivity with a broadcast in onStart() fragment method, when the application starts it works but when there is a rotation of the screen the initializing method returns null and the application crashes with a NullPointerException.


Solution

  • you need to do this in your oncreateView()

    View mView = inflater.inflate(R.layout.fragmentA, container, false);
    

    and than after you Can get your view like this

    textView  = (TextView) mView.findViewById(R.id.textView);
    

    now you are able to use this view.