Tuesday, April 9, 2013

[android help] Why doesn't Android Facebook interface work with Fragments?


As far as I could determine, the Facebook auth API does not support Fragments. Specifically, the onComplete() callback from the Facebook authorize() call works with Activities, but not with Fragments.


So I put together a simple workaround for Fragments. The solution depends on the fact that onActivityResult() is also called in the parent Activity when the authorize() call completes, so you can use it to set up a separate callback mechanism for the Fragment.


First, set up a variable in the parent Activity to carry the target Fragment's name, say



TargetFragment mTargetFragment;


You can initialize it when the Fragment is first instantiated like this:



@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);

String fragmentSimpleName = fragment.getClass().getSimpleName();

if (fragmentSimpleName.equals("TargetFragment"))
mTargetFragment = (TargetFragment)fragment;
}


Then add a couple of lines to the onActivityResult() function:



@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (mTargetFragment != null)
mTargetFragment.myCallBack(requestCode, resultCode, data);
}


Now you can just mimic the code you would ordinarily put in the onComplete() callback in the new myCallBack() function:



public void myCallBack(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);

// other code from your onComplete() function ...
}


I hope this can help someone else. Cheers!



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...