-1

Im trying to implement a Google sign in button:

In my mainactivity I have:

private GoogleApiClient mGoogleApiClient;
//used to identify result
private static final int RC_SIGN_IN = 1253;
private static final String TAG = "SignInActivity";
private TextView responseText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create fragment 
    LoginFragment newFragment = new LoginFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, newFragment);
    //transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit();

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, (GoogleApiClient.OnConnectionFailedListener) this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

   //WONT WORK
   setDefaults()

}

To set the onclicklistener I want to run the following method to set the listener:

public void setDefaults()
{
    responseText = (TextView)findViewById(R.id.googleResponse);
    SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_WIDE);
    findViewById(R.id.sign_in_button).setOnClickListener(this);

}

I cant call it from the oncreate of the mainactivity because findViewById(R.id.googleResponse); will be null.

I do not want to have my logic in the loginfragment but want it in my mainActivity.

How should I set the onclicklisterner to the sign_in_button (which is in the loginfragment) while avoiding a null ptr.

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

1 Answers1

1

From documentation of onResumeFragments:

This is the fragment-orientated version of onResume() that you can override to perform operations in the Activity at the same point where its fragments are resumed. Be sure to always call through to the super-class.

Thus, in this callback you are sure that your fragments are in onResume()d state and view hierarchy is laid out.

But this is not the best solution there. Imho, setting an observer in fragment is way concise. Just create an interface. Make your activity implement that interface and within fragment's onViewCreated() callback call the implementation of that interface.

if (getActivity() instanceof YourInterface) {
    ((YourInterface) getActivity()).performInitialization();
}
azizbekian
  • 60,783
  • 13
  • 169
  • 249