I'm trying to save user details after logging in (with Facebook). I'm able to fetch data but can't save it. I'm using SharedPreferences but can't save it. Data is not lost when I go on some other activity, but when I click back button and re-open this activity, all data is lost. Here is my code:
Profilee.java
public class Profilee extends Fragment {
String email1, birthday1, gender1;
ImageView imageView;
static int itis = 1;
TextView texty;
LoginButton button;
LinearLayout userinput;
private CallbackManager callbackManager;
private TextView textView;
SharedPreferences pref;
private TextView email, birthday, gende;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest graphrequest = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
if (jsonObject != null) {
try {
email1 = jsonObject.getString("email");
gender1 = jsonObject.getString("gender");
birthday1 = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email, gender, birthday");
graphrequest.setParameters(parameters);
graphrequest.executeAsync();
AppEventsLogger.activateApp(getContext());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public Profilee() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Toast.makeText(getContext(), "Create", Toast.LENGTH_SHORT).show();
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profilee, container, false);
button = (LoginButton) v.findViewById(R.id.login_button);
TextView button12 = (TextView) v.findViewById(R.id.edit);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PrifileEdit.class);
i.putExtra("st", email1);
startActivity(i);
}
});
texty = (TextView) v.findViewById(R.id.emo);
imageView = (ImageView) v.findViewById(R.id.asd);
userinput = (LinearLayout) v.findViewById(R.id.userdetail);
int unicode = 0x1F60E;
String emoji = getEmijoByUnicode(unicode);
String text = "We will never post on your wall without permission ";
texty.setText(text + emoji);
Toast.makeText(getContext(), "CreateView", Toast.LENGTH_SHORT).show();
return v;
}
public String getEmijoByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
#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);
email = (TextView) view.findViewById(R.id.emailid);
gende = (TextView) view.findViewById(R.id.gender);
birthday = (TextView) view.findViewById(R.id.birth);
loginButton.setReadPermissions("email");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
Toast.makeText(getContext(), "ViewCreate", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
public void displayMessage(final Profile profile) {
if (itis == 1) {
if (profile != null) {
textView.setText(profile.getName());
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
button.setVisibility(View.GONE);
texty.setVisibility(View.GONE);
userinput.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(textView));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gende));
editor.commit();
}
}
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getContext(), "Start", Toast.LENGTH_SHORT).show();
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}
}
I think this problem is because of displayMessage() method .
when you reopen this Activity , onResume(); method will call , and then displayMessage() .
in displayMessage() you are setting sharedprefrecens values again , and this work cause you lost previous data from this sharedprefrecens.
for solve this problem you must cut onResume codes inside onCreate method
You aren't persisting the data in SharedPreferences correctly. getText() will retrieve the text that is currently displayed in the TextView, allowing you to store it into SharedPreferences.
editor.putString("name", String.valueOf(textView)); // wrong
editor.putString("name", textView.getText().toString()); // right
You can then retrieve the value and display it on screen by calling setText().
String myEmail = pref.getString("email", "qwerty");
textView.setText(myEmail);
Related
I have added Facebook Login code inside fragment. Everything works fine,i can login into my app but when i change fragment or reopen app after login every data are gone i.e email,name,birthday.it doesn't shows any data.so, what should i do to save those data.
code
public class ProfileFragment extends Fragment{
ProfileTracker profileTracker;
RelativeLayout fbbg;
RelativeLayout rl;
LoginButton btnLogin;
CallbackManager callbackManager;
AccessTokenTracker accessTokenTracker;
CircleImageView profilePicture;
TextView email;
TextView gender;
TextView facebookName;
TextView birthday;
SharedPreferences pref;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
add("user_photos");
add("user_birthday");
}};
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState) {
View view = inflater.inflate(R.layout.profile, container, false);
FacebookSdk.sdkInitialize(getActivity());
btnLogin = (LoginButton)view.findViewById(R.id.view);
email = (TextView)view.findViewById(R.id.un2);
facebookName = (TextView)view.findViewById(R.id.username);
birthday = (TextView)view.findViewById(R.id.bd2);
gender = (TextView)view.findViewById(R.id.gnd2);
profilePicture = (CircleImageView)view.findViewById(R.id.profile_image);
rl = (RelativeLayout) view.findViewById(R.id.rl);
fbbg = (RelativeLayout) view.findViewById(R.id.relativeLayout);
callbackManager = CallbackManager.Factory.create();
btnLogin.setReadPermissions(mPermissions);
btnLogin.setFragment(this);
btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("JSON", ""+response.getJSONObject().toString());
try {
fbbg.setVisibility(View.GONE);
rl.setVisibility(View.VISIBLE);
email.setText(object.getString("email"));
gender.setText(object.getString("gender"));
facebookName.setText(object.getString("name"));
birthday.setText(object.getString("birthday"));
Glide.with(getActivity())
.load("https://graph.facebook.com/" + object.getString("id") + "/picture?type=large")
.into(profilePicture);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(facebookName));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gender));
editor.putString("birthday", String.valueOf(birthday));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
facebookName.setText("");
email.setText("");
gender.setText("");
birthday.setText("");
profilePicture.setImageResource(R.drawable.user);
}
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public void onCancel() {
Toast.makeText(getActivity(),"Cancled to Login Facebook", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getActivity(),"Error to Login Facebook", Toast.LENGTH_SHORT).show();
}
}); return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
pref.getString("birthday", "kdhfaj");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
}
After login pic
After reopening app pic
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
AppEventsLogger.activateApp(getActivity());
}
No need to do this.
whenever you are resuming the fragment then that time it is creating the fresh instance of your facebook profile thats why data loss is happening.
on resume just reload fragment dont create new instace.
whenever you get data from facebook api immediately store it to shared preferences. after that you can fetch that data whenever you require.
public UpdateFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_updates, container, false);
listView = (ListView) v.findViewById(R.id.listView);
// define your xml resources here
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
loadUpdates();
}
private void loadUpdates() {
// api call
}
}
Try to embed your code into this fragment lifecycle. it will surely work.
There is no need to add onResume()
just do your stuff in loadUpdates(); method.
I have modified your code wrt SharedPreference.
You can try that.
pref = getActivity().getSharedPreferences("GIVE SOME name TO FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", object.getString("name"));
editor.putString("email", object.getString("email"));
editor.putString("gender", object.getString("gender"));
editor.putString("birthday", object.getString("birthday"));
editor.apply();
Replace above code with your existing code, once you successfully get user profile information from FB
I think your problem is your SharedPreferences was initialized with an Activity. To avoid your data is lost when the Activity destroyed, you should use ApplicationContext().
I made a separated class with SharedPreference like this:
public class SessionManager {
// Shared Preferences reference
public SharedPreferences pref;
// Editor reference for Shared preferences
private Editor editor;
#SuppressWarnings("unused")
private Context context;
int PRIVATE_MODE = 0;
public static final String PREFER_NAME = "login";
public static final String KEY_USER_NAME = "username";
public SessionManager(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getUserName() {
return pref.getString(KEY_USER_NAME, "");
}
public void setUserName(String userName) {
editor.putString(KEY_USER_NAME, userName);
editor.commit();
}
In your Fragment, initializing SharedPreferences with:
sessionManager = new SessionManager(getActivity.getApplicationContext());
saving your data:
session.setUserName(object.getString("name"));
Retrieving data at later times by called:
String userName = session.getUserName();
I have 3 Activity's.
MainActivity has the side_nav_menu (Later I want the circle picture).
FacebookActivity has the facebook SDK and and the Fragment.
BlankFragment has all the facebook login with a txtView that gets the current user name.
Whats the best way to get the user name, picture and email. So I can show it on side_nav_menu.
How this callbackManager works?
FacebookActivity extends to Fragment
private BlankFragment mainFragment;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
printHashkey();
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new BlankFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (BlankFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
public void printHashkey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"BLA BLA BLA BLA BLA BLA",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
And the Fragment
private CallbackManager callbackManager;
private TextView textView;
private ImageView imv;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public BlankFragment() {
}
#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();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#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("public_profile");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void displayMessage(Profile profile){
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
ProfilePictureView profileImage = (ProfilePictureView) getActivity().findViewById(R.id.profilePicture);
if(profile != null){
textView.setText(profile.getName());
profileImage.setProfileId(profile.getId());
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
How can I get user Name, and Picture. Send to MainActivity on the side_nav_menu?
This part here show the pic and the name on the fragment.
private void displayMessage(Profile profile){
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
ProfilePictureView profileImage = (ProfilePictureView) getActivity().findViewById(R.id.profilePicture);
profileImage.setProfileId(profile.getId());
if(profile != null){
textView.setText(profile.getName());
profileImage.setProfileId(profile.getId());
}
}
You should probably save it in SharedPreferences (for image just save path so you can load it from sdcard, or just save image url)
When I'm connected by the facebook login button, I launch a custom dialog (in the onSuccess) and I want to write in this dialog the name of the person connected. It works when I do it in the layout called in onCreate(I make appear the name after connexion). But it doesn't work when I want to write this in the layout called by the dialog after the connexion (but it's the same activity).
Here is my code :
private CallbackManager mCallbackManager2;
private ProfileTracker mProfileTracker2;
private LoginButton loginbutton2;
final Context context = this;
private ProfilePictureView fAvatar2;
private TextView fName2;
private FacebookCallback<LoginResult> mCallback2 = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
/*
LAUNCH DIALOG ABOUT FACEBOOK CONNEXION
*/
// custom dialog
final Dialog dialogFacebookConnexion = new Dialog(context);
dialogFacebookConnexion.setContentView(R.layout.dialog_facebook_connect);
Button dialogButton = (Button) dialogFacebookConnexion.findViewById(R.id.dialogOk);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogFacebookConnexion.dismiss();
Intent intentmainpage = new Intent(InfoAccountActivity.this, MainPageActivity.class);
startActivity(intentmainpage);
}
});
dialogFacebookConnexion.setCanceledOnTouchOutside(false);
int dialogHeight = (int) getResources().getDimension(R.dimen.dialog_height);
int dialogWidth = (int) getResources().getDimension(R.dimen.dialog_width);
dialogFacebookConnexion.getWindow().setLayout(dialogWidth, dialogHeight);
dialogFacebookConnexion.show();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_info_account);
mCallbackManager2 = CallbackManager.Factory.create();
loginbutton2 = (LoginButton) findViewById(R.id.login_button2);
loginbutton2.setBackgroundResource(R.drawable.facebookconnexion);
loginbutton2.setReadPermissions("user_friends");
loginbutton2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
loginbutton2.registerCallback(mCallbackManager2, mCallback2);
fName2 = (TextView) findViewById(R.id.facebookName2);
fAvatar2 = (ProfilePictureView) findViewById(R.id.facebook_avatar2);
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
OnProfileChanged(newProfile);
}
};
}
private void OnProfileChanged (Profile profile) {
if (profile != null) {
try {
fName2.setText(profile.getName());
fAvatar2.setProfileId(profile.getId());
} catch (Exception ex) {
}
} else {
}
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
OnProfileChanged(profile);
}
#Override
public void onStop() {
super.onStop();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager2.onActivityResult(requestCode, resultCode, data);
}
Is it a problem with private or protected ? An information can't be access by the dialog?
In any activity, you can use the following facebook code from their SDK once you have signed into Facebook:
Profile.getCurrentProfile().getName()
Did you try using the Request.newMeRequest using your active open session? It is easy to capture the logged user's profile afterwards.
GraphRequest rq = GraphRequest.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(final GraphUser user, Response response) { ...
...
rq.executeAndWait();
You can retrieve the user's name by user.getName() in the onCompleted method and use it anywhere.
so i created a simple facebook login app following the exact instructions from this video: https://www.youtube.com/watch?v=myWu-q8Q2NA&list=PLonJJ3BVjZW4E1wIRZvuXhbFRGWB1grmh
anyways i am able to sign in but unlike the video, when I sign in, I appear back at the login page, the login button does not change to the logout button,
I click the login button, enter my login details, hit send, then a message says: You have already authorized "LoginExample (app name)". Then I appear back at the login with facebook button.
and on a similar note, I am trying to get a TextView to display a "Welcome", however it does not work, it only works when I do ' android:text="Welcome" '.
Below is my code in a fragment, I do setContentView(activity_fragment); in MainActivity. Again, the Login button appears but the TextView does not.
What is going wrong?
public class MainFragment extends Fragment {
public TextView mTextDetails;
private AccessTokenTracker mtokentracker;
private ProfileTracker mprofiletracker;
CallbackManager mCallBackManager;
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
//TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
//setContentView(R.layout.activity_main);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
//TextView mTextDetails = (TextView) getView().findViewById(R.id.textView);
//mTextDetails.setText("Welcome");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallBackManager = CallbackManager.Factory.create();
AccessTokenTracker tracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken old, AccessToken niw) {
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("welcome " + profile.getName());
}
}
};
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile old, Profile niw) {
}
};
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) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
//loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(mCallBackManager, mCallBack);
TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
mTextDetails.setText("Welcome");
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
}
#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);
}
}
I have the follow code, but I don't know which is the method that execute when I push in Logout. I only need know which is the method that execute in logout. Or another solution? Thanks for all :) dasasa
public class FBLoginFragment extends Fragment implements IServiceCallback {
private CallbackManager callbackManager;
private TextView textView;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public FBLoginFragment() {
}
#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) {
}
};
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
displayMessage(newProfile);
if(newProfile != null){
register(newProfile);
}
}
};
accessTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.facebook_fragment, container, false);
}
#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(Arrays.asList("public_profile", "user_friends"));
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (callbackManager.onActivityResult(requestCode, resultCode, data))
return;
}
private void displayMessage(Profile profile){
if(profile != null){
textView.setText(profile.getName());
}
}
private void register(Profile profile){
if(profile != null){
new Register(this).run(profile);
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onSuccess(JSONObject obj, String method) throws JSONException {
User user = new User(obj);
user.insert();
//Intent intent = new Intent(getActivity(), Update.class);
//startActivity(intent);
}
#Override
public void onError(String error) {
}
You need to get the active Session, then then call closeAndClearTokenInformation().
You can get the currently active session via Session.getActiveSession().
Try this method to logout from facebook programmatically in android
/**
* Logout From Facebook
*/
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}