0

I am new to Android and having an issue in initializing Fragment I am looking at two lines of code and cannot figure out the actual difference between these two approaches and which one to opt. Kindly suggest

 1) SignUpFragment fragment = new SignUpFragment();
 2) SignUpFragment fragment = SignUpFragment.newInstance();
Samuel Robert
  • 10,106
  • 7
  • 39
  • 60

3 Answers3

0

I personally use the first one as it will make a new object of signupFragment ,while the second option will make a new instance of that class.The difference between both is defined in the below link.

https://stackoverflow.com/questions/3323330/difference-between-object-and-instance
Saad Maqbool
  • 301
  • 2
  • 10
0

If you have no arguments to pass to fragment you can use first one.

SignUpFragment fragment = new SignUpFragment();

But if you have arguments you can use factory methods such as second one to hide creating bundle and putting the arguments' boilerplate codes.

ProfileFragment fragment = ProfileFragment.newInstance(userId);


public class ProfileFragment extends Fragment {
    public static ProfileFragment newInstance(int userId) {
          Bundle args = new Bundle();
          args.putInt("userId", userId);
          ProfileFragment fragment = new ProfileFragment();
          fragment.setArguements(args);
          return fragment;
    }
}
Samuel Robert
  • 10,106
  • 7
  • 39
  • 60
0

1) SignUpFragment fragment = new SignUpFragment();

You should only use in case you do NOT need to create SignUpFragment instance more frequently.

2) SignUpFragment fragment = SignUpFragment.newInstance();

This is more recommended approach. In which, you would going to follow Singleton pattern for creating Instance of your class and more generic methods can be created in future if needed.

Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107