bencallis bencallis - 1 year ago 358
Android Question

getView returning null when fragment has been created from an activity

I have a working tablet application which I am now trying to make work on phones too.
On a table there is two fragments on the screen a list fragment and a details fragment.
When on a phone the list fragment appears and creates a new activity when a list item is pressed.
This activity simply creates the fragment in the

method and commits it to the screen as follows.

// Place an DeallDetailsFragment as our content pane
DealDetailsFragment f = new DealDetailsFragment();
getFragmentManager().beginTransaction().add(, f).commit();

This is working as expected however from within this activity I need to tell the fragment what details to load and display. In my DealDetailsFragment class I have a
method which updates the content as follows.

if (deal==null) { // could be null if user presses the loading deals list item before it loads
if (dealTitle==null) { // get the view objects only once
holder = new ViewHolder();
holder.dealHeat=(TextView) getView().findViewById(;
holder.dealPrice=(TextView) getView().findViewById(;
holder.dealRetailer=(TextView) getView().findViewById(;
holder.dealTitle=(TextView) getView().findViewById(;
holder.dealDesc=(TextView) getView().findViewById(;
holder.goToButton= (LinearLayout) getView().findViewById(;
holder.dealImage=(ImageView) getView().findViewById(;
holder.postedBy=(TextView) getView().findViewById(;
holder.datePosted=(TextView) getView().findViewById(;

is returning null when the application is ran on a phone where there is only a single fragment shown.

Any ideas? Unfortunately, there is not many fragment examples available online.

Answer Source

Move your method call to be executed during onCreateView, and use the view you are inflating for reference instead of getView(). See the fragment lifecycle for more information:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download