Basically I have my fragment
public class FragmentDashboard extends Fragment {
public static FragmentDashboard newInstance() {
FragmentDashboard frag = new FragmentDashboard();
return frag;
}
public void updateData(Object object){
myTextView.setText(object.getField);
//update views with object values
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
myTextView = (TextView) view.findViewById(R.id.myTextView );
}
}
Then in my activity I need to update data I do:
FragmentDashboard fragmentDashboard = (FragmentDashboard) getSupportFragmentManager().findFragmentById(R.id.layFragment);
fragmentDashboard.updateData(myObject)
This works good if I am making the call on my activity after the Fragment has been displayed (like from an asynctask on completed).
The problem I am running into is having to run the updateData right after I add the fragment on my activity's onCreate().
final FragmentTransaction ft = fragmentManager.beginTransaction();
FragmentDashboard fragmentDashboard = FragmentDashboard.newInstance();
ft.replace(R.id.layFragment, fragmentDashboard);
ft.commit();
fragmentDashboard.updateData(myObject)
Running this I get a NPE because the fragment's onCreateView
hasn't been run yet and the myTextView
is not initialized
I don't want to add parameters on newInstance as I'd like to avoid making the object as parcelable. Any ideas ?
You can use a local field to contains your data and use it in your
onCreateView
method :And in onViewCreated