Skip to content Skip to sidebar Skip to footer

Update Fragment Data After NewInstance()

Basically I have my fragment public class FragmentDashboard extends Fragment { public static FragmentDashboard newInstance() { FragmentDashboard

Solution 1:

You can use a local field to contains your data and use it in your onCreateView method :

public class FragmentDashboard extends Fragment {

    private Object myData=null;
    private TextView myTextView = null;

    public static FragmentDashboard newInstance() {
        FragmentDashboard frag = new FragmentDashboard();
        return frag;
    }

   public void updateData(Object object){
       myData = object;
       if(myTextView != null)
           myTextView.setText(myData);
   }

   @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 );
       if(myData != null && myTextView != null)
           myTextView.setText(myData);
   }
}

Solution 2:

It isn't a good practice to set Data like updateData(Object ) . Make your model class parcelable or serializable and pass it in putExtra and get it in onViewCreated.

    public static FragmentDashboard newInstance(Object object) {
                Bundle args = new Bundle();
                args.putParcelable("yourModelClass",object);
                FragmentDashboard frag = new FragmentDashboard();
                frag.setArguments(args);
                return frag;
     }    

And in onViewCreated

if(getArguments != null)
    yourModelClassObject = getArguments().getParcelable("yourModelClass");

 if(yourModelClassObject != null)
     textView.setText(yourModelClassObject.getField());

I have written code orally . May contain mistakes.


Post a Comment for "Update Fragment Data After NewInstance()"