sasan sasan -4 years ago 84
Android Question

onCreateView does not fired in Fragment

At first the problem was getView() always returns null in my fragment . so as others offer I used a View in onCreateView to get view like this :

private View vv ;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
vv = inflater.inflate(R.layout.fragment_exam_page2, container, false); ;
return vv ;


so I could use vv instead of getView() . But now I see that onCreateView does not get called at all !
in my activity I do this :

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
TwoLineOptionsFragment twoLineOptionsFragment = new TwoLineOptionsFragment();
transaction.replace(, twoLineOptionsFragment).commit();

twoLineOptionsFragment.updateOptions(question.AnswerOptions) ;// my public function doing stuff ...

so where is the problem ?

EDIT : here is my function if matters :

public boolean updateOptions(ArrayList<Exam.Question.Answer> answers)

QuestionOptionView optionView = (QuestionOptionView)(vv.findViewById( ;
//QuestionOptionView optionView = (QuestionOptionView)(getView().findViewById( ;
return reue ;
// ...

Answer Source

onCreateView() of Fragment will get called always. The problem in your case is you are trying to access the view object before onCreateView() get called. The following get executed too early.

 twoLineOptionsFragment.updateOptions(question.AnswerOptions) ;

Don't call Fragment methods directly from the activity, because you may not sure that Fragment is ready or not. You should move your logic into Fragment class itself and provide a callback to Activity so that you can pass results back to the Activity.

In your case, you can pass answers.get(0).AnswerText value as an argument to Fragment and display it on the TextView. cheers :)

TwoLineOptionsFragment f = new TwoLineOptionsFragment();
Bundle args = new Bundle();
args.putString("arg", answers.get(0).AnswerText);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download