logout from facebook generating error - android

in my application, I can easily login but when ever I click on logout button, it gives me an error
I want when I click on logout button,and after that I click on login button,I get the same dialog box appear for login that ask for emailid and the password.but when I click on login button after logout, it only show me the toast displaying you are already login.
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
private AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(getApplication(), "already login", Toast.LENGTH_LONG).show();
//logoutFromFacebook();
}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Session.getActiveSession() != null) {
//editor.remove("access_token");
mPrefs.edit();
editor.clear();
editor.commit();
Session.getActiveSession().closeAndClearTokenInformation();
} Session.setActiveSession(null);
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
logcat
04-17 11:05:53.375: E/AndroidRuntime(12371): FATAL EXCEPTION: Thread-1443
04-17 11:05:53.375: E/AndroidRuntime(12371): java.lang.IllegalArgumentException: Invalid context argument
04-17 11:05:53.375: E/AndroidRuntime(12371): at android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.internal.Utility.clearCookiesForDomain(Utility.java:286)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.internal.Utility.clearFacebookCookies(Utility.java:310)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.Session.closeAndClearTokenInformation(Session.java:614)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.android.Facebook.logoutImpl(Facebook.java:665)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.android.AsyncFacebookRunner$1.run(AsyncFacebookRunner.java:89)
facebook.java
#Deprecated
public String logout(Context context) throws MalformedURLException, IOException {
return logoutImpl(context);
}
String logoutImpl(Context context) throws MalformedURLException, IOException {
checkUserSession("logout");
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
String response = request(b);
long currentTimeMillis = System.currentTimeMillis();
Session sessionToClose = null;
synchronized (this.lock) {
sessionToClose = session;
session = null;
accessToken = null;
accessExpiresMillisecondsAfterEpoch = 0;
lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis;
sessionInvalidated = false;
}
if (sessionToClose != null) {
sessionToClose.closeAndClearTokenInformation();
}
return response;
}

Related

Facebook login in fragment

I would like to use Facebook login in my App. I have just registred app and added SDK to project. However, I tried to follow the tutorial from documentation but nothing worked (I need to get ID and email from profile and send to to my server).
Fragment
public class LoginFragment extends Fragment {
#BindView(R.id.ivLogo) ImageView ivLogo;
#BindView(R.id.email) EditText edEmail;
#BindView(R.id.password) EditText edPassword;
#BindView(R.id.btnFbLogin) LoginButton btnFbLogin;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
String email, password, ID;
User user;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i("success", "success");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login_screen, container, false);
ButterKnife.bind(this, view);
btnFbLogin.setReadPermissions("email");
btnFbLogin.setFragment(this);
// Callback registration
btnFbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
((MainActivity) getActivity()).getSupportActionBar().hide();
}
private void FBcallback() {
FacebookCallback<LoginResult> callback = 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) {
try {
String email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException e) { }
};
btnFbLogin.setReadPermissions("email");
btnFbLogin.registerCallback(callbackManager, callback);
}
private void loginEmail() {
FactoryAPI.getInstanceLogin().login("hardcoded mail", "hardcoded password").enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), R.string.email_password_is_not_right, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
private void loginFB() {
FactoryAPI.getServieFBlogin().loginFB(email, ID).enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Log.e("error", "error");
}
});
}
public void getEmailPassword() {
email = edEmail.getText().toString();
password = edPassword.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(getContext(), R.string.empty_properties, Toast.LENGTH_SHORT).show();
}
}
public static boolean emailValidation(CharSequence target) {
return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public void startActivity() {
Intent intent = new Intent(getContext(), AccountActivity.class);
intent.putExtra("account", user);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
#OnClick({R.id.sign_up_email, R.id.btnFbLogin})
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_up_email:
loginEmail();
case R.id.btnFbLogin:
break;
}
}
private void getProfile(Profile profile){
if(profile != null){
ID = profile.getId();
}
}
}
As your facebook login is in Fragment not in activity, so the
callback comes in onActivityResult() of Activity in which this fragment attached.
You can check this after override the onActivityResult() of your activity, and put a debug point there.
After you getting result in your activity onActivityResult() method, you can send it to your fragment's onActivityResult().
Hope this will help.
First of all if you are using LoginButton then you don't need to register with LoginManager. Here is the sample
//Using Facebook's LoginButton
//Register Callback
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email")); //set permissions as public_profile, email, etc
loginButton.setFragment(this); //If you are using in a fragment
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
Now with LoginManager when using Custom Button to login instead of FB's LoginButton
//To check if you are already logged In
boolean loggedIn = AccessToken.getCurrentAccessToken() == null;
// To Manually login. This will launch facebook's login screen.
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile","email"));
In both the cases, for Fragment or Activity you need to handle onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}

Using Shared Preferences with Log in with Facebook

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);

I dont know how using LOGOUT in FACEBOOK API ANDROID

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
}
}

How to get Facebook details after log-in in android?

I am building an android application where user log-in in Facebook
page.
Here is the code -
package loginpck;
public class MainActivity extends Activity {
ImageView btnfb;
// Your Facebook APP ID
private static String APP_ID = "appid";
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnfb = (ImageView) findViewById(R.id.btnfacebook);
btnfb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
loginToFacebook();
}
});
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.chiang_mai,
R.drawable.himeji,
R.drawable.petronas_twin_tower,
R.drawable.ulm
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#SuppressWarnings("deprecation")
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
}
When I move to other Activity I need to toast the user details like
name, image and profile detail's.
How can I get the user detail's ?
Here is second activity :
public class BallDropActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.balldroplayout);
}
}
first create your project and get app. id then pass the cod in your code like this
public static final String mAPP_ID = "Your APP ID";
Facebook mFacebook= new Facebook(mAPP_ID);
and setOnClickListener on your button in On Create()
// facebook login button click event
try{
//mFacebook.logout(LoginActivity.this);
((Button)findViewById(R.id.loginPageFaceBookButton)).setOnClickListener(loginButtonListener);
SessionStore.restore(mFacebook,LoginPage.this);
}
catch (Exception e) {
Toast.makeText( LoginPage.this,"Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}}
// loginButtonListener
//----------------------------------------------
private OnClickListener loginButtonListener = new OnClickListener()
{
public void onClick( View v )
{
if(!mFacebook.isSessionValid() )
{
mFacebook.authorize(LoginPage.this, new String[] {"publish_stream","email","user_groups","read_stream","user_about_me","offline_access"},Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
else
{
try
{
JSONObject json = Util.parseJson(mFacebook.request("me"));
facebookID = json.getString("id");
facebookEmail = json.getString("email");
faceBooklastName=json.getString("last_name");
faceBookFirstName=json.getString("first_name");
}
catch (Exception e)
{
// TODO: handle exception
//Toast.makeText( LoginActivity.this,"Exception FB "+e.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error )
{
Toast.makeText( LoginPage.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}
}};
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
// DialogListener CLASS STATRT HERE.
public final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
try
{
JSONObject json = Util.parseJson(mFacebook.request("me"));
facebookID = json.getString("id");
facebookEmail = json.getString("email");
SessionStore.save(mFacebook, LoginPage.this); Toast.makeText( LoginPage.this,"facebookID :"+facebookID+" \n "+"facebookEmail : "+facebookEmail, Toast.LENGTH_SHORT).show();
}
catch( Exception error )
{
Toast.makeText( LoginPage.this, error.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error )
{
Toast.makeText( LoginPage.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
public void onFacebookError(FacebookError error) {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.1"+error.toString(), Toast.LENGTH_LONG).show();
}
public void onError(DialogError error) {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.2"+error.toString(), Toast.LENGTH_LONG).show();
}
public void onCancel() {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.3", Toast.LENGTH_LONG).show();
}
/****** Facebook Login End *******/
}

Why Facebook login page does not appear when I tried to re-login after I logged out in Android?

I followed this tutorial http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/ to connect Facebook to my Android application. Instead of having many buttons, I have a button that will be used for both login and logout.
1) The first time I run the class, I could login and then logout successfully. And when I click on the same button to login again, the login page would not appear, however the Toast text "LOGGING IN" appear, which is after loginToFacebook() function in my if-else. Hence, I assume, it should have run the facebook login page like the first time I run the class. But the login page does not appear.
What did I do wrong? And what should I do?
2) And how do I display the username in String fbLoggedIn after logged in instead of the text "CONNECTED!!" ?
public class FacebookActivity extends Activity{
private static String APP_ID = "";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
private Button backButton;
private String name = "CONNECTED!!";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_share);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
RelativeLayout fbButton = (RelativeLayout) findViewById(R.id.fbLayout);
fbButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!facebook.isSessionValid())
{
System.out.println("Not Connected. Clicked and Login.");
loginToFacebook();
Toast.makeText(getApplicationContext(), "LOGGING IN", Toast.LENGTH_LONG).show();}
else
{
System.out.println("Connected. Logged Out.");
logoutFromFacebook();
Toast.makeText(getApplicationContext(), "LOGGED OUT", Toast.LENGTH_LONG).show();}
}
});
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
TextView fbUser = (TextView) findViewById(R.id.fbUser);
fbUser.setVisibility(View.VISIBLE);
String fbLoggedIn = name;
fbUser.setText(fbLoggedIn);
Toast.makeText(getApplicationContext(), "LOGGED IN AS " + name, Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) { }
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) { }
#Override
public void onMalformedURLException(MalformedURLException e, Object state) { }
#Override
public void onFacebookError(FacebookError e, Object state) { }
});
}
//logout from Facebook
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#Override
public void onIOException(IOException e, Object state) { }
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) { }
#Override
public void onMalformedURLException(MalformedURLException e, Object state) { }
#Override
public void onFacebookError(FacebookError e, Object state) { }
});
}
Just to be clearer, I set my if-else like this (extracted from the complete codes above).
RelativeLayout fbButton = (RelativeLayout) findViewById(R.id.fbLayout);
fbButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!facebook.isSessionValid())
{
System.out.println("Not Connected. Clicked and Login.");
loginToFacebook();
Toast.makeText(getApplicationContext(), "LOGGING IN", Toast.LENGTH_LONG).show();}
else
{
System.out.println("Connected. Logged Out.");
logoutFromFacebook();
Toast.makeText(getApplicationContext(), "LOGGED OUT", Toast.LENGTH_LONG).show();}
}
});
This is the behavior that Facebook wants you to take with their API.Your login method checks to see if you have already signed in once and that the facebook session is active. If the session is active then it sets the properties of the facebook object and connects it behind the sences so that the login page does not show again.
So you're not doing anything wrong, it's suppose to happen this way.

Categories

Resources