Cannot open activity from Fragment inside onSuccess - java

My issue is very simple, I want users to login using Facebook. After a successful login, grab some details and pass it on another activity. I have my new class in manifeset. I see the log for Log.v("facebook - profile", profile.getFirstName()); I'm quite baffled about what's going on. I have no errors either. I'm passing my activity in the onSuccess.
public class MainActivityFragment extends Fragment {
TextView textview;
private AccessTokenTracker tokenTracker;
private ProfileTracker profileTracker;
private CallbackManager mCallbackManager;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
if(Profile.getCurrentProfile() == null) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
Log.v("facebook - profile", profile2.getFirstName());
profileTracker.stopTracking();
}
};
profileTracker.startTracking();
}
else {
Profile profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
//get info to pass to next activity
String[] profileDetailsArray = new String [5];
profileDetailsArray[0] = profile.getFirstName();
profileDetailsArray[1] = profile.getLastName();
profileDetailsArray[2] = profile.getId();
Bundle arrayBundle = new Bundle();
arrayBundle.putStringArray("profileDetails",profileDetailsArray);
Intent intent = new Intent(getActivity(),LandingPage.class);
intent.putExtras(arrayBundle);
startActivity(intent);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "public_profile"));
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager,mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume(){
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onStop(){
super.onStop();
}
}

Related

Android facebook force logout

I wan't to force logout from facebook when I exit the application so I have to login every time I start the application. If that is not possible I need help with checking if a user is already logged in.
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
if (object != null) {
name = object.getString("first_name") + " "+object.getString("last_name");
email = object.getString("email");
mTextDetails.setText("Welcome " + name);
editor.putString("username", name);
editor.putString("email", email);
editor.apply();
}
} catch (JSONException e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email, first_name, last_name, gender");
request.setParameters(parameters);
request.executeAsync();
}
// }
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
public MainFragment() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mTextDetails = (TextView) view.findViewById(R.id.text_details);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email");//Only ask if you must
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
sharedPref = this.getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
editor = sharedPref.edit();
name = sharedPref.getString("username", "");
email = sharedPref.getString("email","");
if (name != "") {
mTextDetails.setText(name);
}
// Toast.makeText(getActivity(), sharedPref.getString("username", ""), Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), sharedPref.getString("email", ""), Toast.LENGTH_LONG).show();
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
You can use this LoginManager.getInstance().logOut();

I need call another activity automatic, more not know where to put code, facebook login

Sorry my english ! need call another activity automatic, more not know where to put code, "facebook login sdk" It how is code, "startActivity" not function
/** * A placeholder fragment containing a simple view. */
public class MainFragment extends Fragment {
private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("KeyHash", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onCancel() {
Log.d("KeyHash", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("KeyHash", "onError " + e);
}
};
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
mTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setupTextDetails(view);
setupLoginButton(view);
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupTextDetails(View view) {
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker() {
mTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Log.d("KeyHash", "Welcome" + currentAccessToken);
}
};
}
private void setupProfileTracker() {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Log.d("KeyHash", "Welcome" + currentProfile);
mTextDetails.setText(constructWelcomeMessage(currentProfile));
}
};
}
private void setupLoginButton(View view) {
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
mButtonLogin.setFragment(this);
mButtonLogin.setReadPermissions("public_profile,user_friends,email");
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
return stringBuffer.toString();
}
}
If you are trying to start an activity as soon as the user successfully logs in, you can call startActivity(intent) in the onSuccess(LoginResult loginResult) method of the FacebookCallback.
try this in onSuccess method
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String id = object.getString("id");
Intent redirect=new Intent(Login_Activity.this,anotheractivity.class);
startActivity(redirect);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Wait until callback of request is completed, Facebook-SDK android

I have the following class that I instantiate from my fragment:
public class FacebookLogin {
private CallbackManager mCallbackManager;
private LoginButton lButton;
private AccessToken accessToken;
private Profile profile;
private static final String TAG = "FacbookLogin";
public FacebookLogin(Context c) {
FacebookSdk.sdkInitialize(c);
mCallbackManager = CallbackManager.Factory.create();
Log.i(TAG, " Constructor called");
}
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
profile = Profile.getCurrentProfile(); //Access the profile who Is the person login i
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
Log.e(TAG, e.getMessage());
}
};
public void setCallback(LoginButton lButton) {
lButton = lButton;
lButton.registerCallback(mCallbackManager, mCallback);
Log.i(TAG, " setCallback called");
}
And here Is my fragment-class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fLogin = new FacebookLogin(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.login, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
final LoginButton loginButton = (LoginButton) getView().findViewById(R.id.login_button);
final TextView infoText = (TextView) getView().findViewById(R.id.text_details);
loginButton.setFragment(this);
loginButton.setReadPermissions("user_friends");
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
profile = fLogin.getProfile();
if (profile != null) {
Log.i(TAG, profile.getName()); //Call this after the callback request Is finished
} else {
Log.i(TAG, "NULL....... inside onresume");
}
}
});
}
I want to call profile = fLogin.getProfile(); after the callback request is complete. But I don't know how to do this. I have read about the onComplete();, but I don't know how to Implement It here.

Show view contents after successfully authentication

How and Where do I set view contents to be displayed for persons who has successfully been authenticated using Facebook SDK?
After the persons has logged In, I want to display a User profile view.
I have tried to Instansiate a new fragment like the code below, but that don't work. The text "Fish" Is not displayed.
public class LoginFragment extends Fragment {
private CallbackManager mCallbackManager;
private static final String TAG = "Facebook";
private LoginButton login;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile(); //Access the profile who Is the person login in
if(profile != null) {
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new LoggedInFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
}
};
public LoginFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
//Ask the use for permission to access friends
loginButton.setReadPermissions("user_friends");
//Because we work with fragments
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Here IS fragement that the user should see when he/she Is logged In:
package com.waddapp.bryan.waddapp;
public class LoggedInFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.logged_in, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
TextView mTextDetails = (TextView)view.findViewById(R.id.text_details);
mTextDetails.setText("FISH");
}
public LoggedInFragment() {
}
}
Anyone who can explain how acomplish this?

How to login Facebook using nested fragment in Android

I have nested fragment like the following.
MainActivity
FragmentA
FragmentA1
FragmentA3
FragmentA2
FragmentB
FragmentB1
I want to login facebook from FragmentA3. But can not.
In FragmentA3, my app stop in onResume after called onActivityResult.
What should I do?
FragmentA3
public class FragmentA3 extends Fragment {
public static final String TAG = FragmentA3.class.getCanonicalName();
private UiLifecycleHelper mFbSdkUiHelper;
private OnLoggedListener mCallback;
private final List<String> permissions;
public OthersFBLogin() {
// Required empty public constructor
permissions = Arrays.asList("basic_info", "email");
}
public interface OnLoggedListener {
//Callback to notify about login success.
public void onLoginSuccess();
}
private final Session.StatusCallback mSessionCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.d(TAG,"onSessionStateChange");
if (state.isOpened()) {
mCallback.onLoginSuccess();
} else if (state.isClosed()) {
if (session != null) {
session.closeAndClearTokenInformation();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate");
super.onCreate(savedInstanceState);
mFbSdkUiHelper = new UiLifecycleHelper(getActivity(), mSessionCallback);
mFbSdkUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG,"onCreateView");
View rootView = inflater.inflate(R.layout.others_fblogin, container, false);
LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
loginButton.setFragment(this);
loginButton.setReadPermissions(permissions);
return rootView;
}
#Override
public void onAttach(Activity activity) {
Log.d(TAG,"onAttach");
super.onAttach(activity);
try {
mCallback = (OnLoggedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLoggedListener in order to use this fragment");
}
}
#Override
public void onResume() {
Log.d(TAG,"onResume");
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
mFbSdkUiHelper.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
Log.d(TAG,"onPause");
super.onPause();
mFbSdkUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mFbSdkUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
mFbSdkUiHelper.onSaveInstanceState(outState);
}
}
LogCat
D/com.example.sample.FragmentA3 ﹕ onAttach
D/com.example.sample.FragmentA3 ﹕ onCreate
D/com.example.sample.FragmentA3 ﹕ onCreateView
D/com.example.sample.FragmentA3 ﹕ onResume
D/dalvikvm ﹕ GC_FOR_ALLOC freed 764K, 10% free 7977K/8816K, paused 3ms, total 6ms
W/GooglePlayServicesUtil ﹕ Google Play services is missing.
D/com.example.sample.FragmentA3 ﹕ onPause
D/com.example.sample.FragmentA3 ﹕ onSessionStateChange
W/EGL_emulation ﹕ eglSurfaceAttrib not implemented
I/Choreographer ﹕ Skipped 174 frames! The application may be doing too much work on its main thread.
D/com.example.sample.MainActivity﹕ onActivityResult
D/com.example.sample.FragmentA ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onResume
Please try this solution:
public class FragmentA3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Fragment fragmentA1 = this.getParentFragment();
Fragment fragmentA = fragmentA1.getParentFragment();
loginButton.setFragment(fragmentA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA1 extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA3 !=null)
mFragmentA3.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA1 !=null)
mFragmentA1.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
Step 1: Add the below code in the fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
context = getContext();
FacebookSdk.sdkInitialize(context);
View view = inflater.inflate(R.layout.fragment_facebook_sign_in, container, false);
}
Step 2: Handle the callback of facebook.
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
String lastName = object.getString("last_name");
profile_link = object.getString("link");
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
Utility.logMe("\nFacebook_user_mail:"+email +"\nFacebook_user_Fname:"+firstName+"\nFacebook_user_Lname:"+lastName+"\nFacebook_user_Image:"+profilePicUrl+"\nProfile_link:"+profile_link);
if(email != null && email.length()> 0)
{
LoginManager.getInstance().logOut();
signUpFacebook(firstName, lastName, email, profilePicUrl, profile_link);
}
else {
Toast.makeText(getActivity(), "Email not present to login", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Email Not Exist for this user on Facebook.", Toast.LENGTH_LONG).show();
progressDialog = new ProgressDialog(getContext());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,link,name,email,birthday,gender,first_name,last_name,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
Step 3:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
//displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
Step 4:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
Step 5:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Step 6:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
for (Fragment fragmento : allFragments) {
if (fragmento instanceof TwitterSignIn) {
((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof GooglePlusSignIn) {
((GooglePlusSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof FacebookSignIn) {
((FacebookSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
}
}

Categories

Resources