Android:Cannot logout from facebook and pass status - android

Problem1:When i click login button i can log in,give status.but when i press logout button it does not logout.So,how will i logout from facebook?
Problem2:I got a string str.I want to pass it in facebook's textfield (like we send messages by intent).How will i do that.
main class:
`
public class MainActivity extends Activity {
private static String APP_ID = "xxxxxxx";
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
ImageButton btnFbLogin;
ImageButton btnFbLogout;
Button btnPostToWall;
String str="I want this to pass";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (ImageButton) findViewById(R.id.btn_fblogin);
btnFbLogout = (ImageButton) findViewById(R.id.btn_fbLogout);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
logoutFromFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
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);
btnFbLogin.setVisibility(View.INVISIBLE);
btnFbLogout.setVisibility(View.VISIBLE);
btnPostToWall.setVisibility(View.VISIBLE);
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() {
}
#Override
public void onComplete(Bundle values) {
acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
btnFbLogin.setVisibility(View.INVISIBLE);
btnFbLogout.setVisibility(View.VISIBLE);
btnPostToWall.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
}
#Override
public void onFacebookError(FacebookError fberror) {
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void postToWall() {
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
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) {
runOnUiThread(new Runnable() {
#Override
public void run() {
btnFbLogin.setVisibility(View.VISIBLE);
btnFbLogout.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
}
});
}
}
#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) {
}
});
}
}`
when i click the logout button it says:
`
08-14 14:46:59.849: D/Image Button(284): button Clicked
08-14 14:46:59.869: D/Facebook-Util(284): GET URL: https://api.facebook.com/restserver.php? method=auth.expireSession&format=json
08-14 14:47:00.399: D/Logout from Facebook(284): {"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"auth.expireSession"},{"key":"format","value":"json"}]}
`

just clear sharedprefrence and clear cookig to logout from facebook
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
Util.clearCookies(youractivity.this);
// your sharedPrefrence
Editor editor = context.getSharedPreferences("MYFB_TOKEN", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
}
});
OR
See this How can i logout from facebook when i click logout button

use this it is working for me
facebook.logout(this);
in Facebook SDK Facebook.java
public String logout(Context context) throws MalformedURLException, IOException {
Util.clearCookies(context);
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
String response = request(b);
setAccessToken(null);
setAccessExpires(0);
return response;
}

Related

logging in then out from facebook causes a crash when trying to reLogin android

I added a login button to my application, it's working just fine, but my problem is when I added a logout button in the next activity, it's logging out but when I try to login again my application crashes!
I used this code to logout : LoginManager.getInstance().logOut();
and here's how my java code of the activity where I login:
public class ConnexionActivity extends AppCompatActivity {
Button b_bb, b_back, ee, b_inscrp_formulaire, fb;
EditText tb_pseudo, tb_mdp;
int id;
String name, gender, email, birthday;
private LoginButton loginButton;
private CallbackManager callbackManager;
Profile profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
/*List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");*/
setContentView(R.layout.activity_connexion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
b_inscrp_formulaire = (Button) findViewById(R.id.b_inscrip_formulaire);
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Non-Connecté : connexion interrupu!!", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_LONG).show();
}
});
b_bb = (Button) findViewById(R.id.b_bb);
b_back = (Button) findViewById(R.id.b_back);
tb_pseudo = (EditText) findViewById(R.id.textbox_pseudo);
tb_mdp = (EditText) findViewById(R.id.textbox_mdp);
/////////////
ee = (Button) findViewById(R.id.button);
////////////
b_bb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
b_bb.setBackgroundResource(R.drawable.button_bb_selec);
break;
}
case MotionEvent.ACTION_UP: {
b_bb.setBackgroundResource(R.drawable.button_bb);
break;
}
}
return false;
}
});
b_bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isAuthorized()) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", tb_pseudo.getText().toString());
startActivity(menu_p);
} else {
openDialog();
}
}
});
b_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnexionActivity.this.finish();
}
});
ee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", "Easter");
startActivity(menu_p);
}
});
b_inscrp_formulaire.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, InscriptionActivity.class);
startActivity(menu_p);
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Non-Connecté : connexion interrupu!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this,
Arrays.asList("public_profile","user_friends", "email"));
/*facebook permissions : "user_photos", "email", "user_birthday", "public_profile"*/
profile = Profile.getCurrentProfile().getCurrentProfile();
//to verify if a login happened or not!!
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}
}
});
//To log out of FB:
/*LoginManager.getInstance().logOut();*/
//TODO: check if the user is logged in or not
/* profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}*/
}
private Boolean isAuthorized() {
if (tb_pseudo.getText().toString().equals("Admin")
&& tb_mdp.getText().toString().equals("0000")
) {
return true;
} else
return false;
}
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Mauvaise combinaison \"Pseudo\", \"Mot de passe\"");
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
//showing infos about the connected client!!
//Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
}
});
Bundle b = new Bundle();
b.putString("fields", "id,email,first_name,last_name,picture.type(large)");
request.setParameters(b);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Finaly I got an answer to this:
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
fb = (Button) findViewById(R.id.fb);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Non-Connecté : connexion interrupu!!", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_LONG).show();
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Non-Connecté : connexion interrupu!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this,
Arrays.asList("public_profile", "user_friends", "email"));
/*facebook permissions : "user_photos", "email", "user_birthday", "public_profile"*/
profile = Profile.getCurrentProfile().getCurrentProfile();
//to verify if a login happened or not!!
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}
}
});

How to connect to facebook from my application

I'm developing android app and i want user to connect Facebook when he open the app for the first time using Facebook SDK.
Then i want to post to the Facebook wall with specific message from my app. I try to use Facebook sdk with my app.I have made integration between mp app and Facebook sdk but i don't know how to do the task that log in to Facebook and post to the wall with the specific message.I search stackoverflow for this task and i found this code but i can't understand it
and it doesn't for me
public class MainActivity extends Activity {
Facebook facebookClient;
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebookClient=new Facebook("fb_App_id");
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
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) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "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", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
You should refer to the following question on SO.
Facebook login and post
This code works. It will definitely solve your problem.
Try to use Android Simple Facebook (https://github.com/sromku/android-simple-facebook) - it's a layer to make the usage of Facebook SDK easier. According to the documentation, the login process would be something like this:
Initialize callback listener:
OnLoginListener onLoginListener = new OnLoginListener() {
#Override
public void onLogin() {
// change the state of the button or do whatever you want
Log.i(TAG, "Logged in");
}
#Override
public void onNotAcceptingPermissions(Permission.Type type) {
// user didn't accept READ or WRITE permission
Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
}
/*
* You can override other methods here:
* onThinking(), onFail(String reason), onException(Throwable throwable)
*/
};
Login:
mSimpleFacebook.login(onLoginListener);

Opening Facebook login Dialog on Button Click

Hi Everyone I am intergrating facebook login to my app. I have searched a lot and I am able to login I have used this link: https://developers.facebook.com/docs/mobile/android/build/#register
All I want to do is that When I click on a Button then facebook dialog must appear intead of just opening the activity (HomeActivity) following is my code.
public class HomeActivity extends Activity {
Facebook facebook = new Facebook("114987225319269");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button more = (Button) findViewById(R.id.button1);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
facebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
}
Use this code
Button more = (Button) findViewById(R.id.button1);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (! facebook.isSessionValid()) {
facebook.authorize(HomeActivity.this, PERMISSIONS, new LoginDialogListener());
});
}
this is the login dialog listener
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
In your Manifest
<activity
android:theme="#android:style/Theme.Translucent"
android:name=".HomeActivity "
>
This will change your activity theme into Dialog theme. Hope this helps...
This is all what you need:
public class BaseActivity extends Activity
{
public AsyncFacebookRunner mAsyncRunner;
public Facebook facebook;
public SharedPreferences mPrefs;
public static String appId = "123344";
SharedPreferences.Editor editor;
private void initialize()
{
facebook = new Facebook(appId);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void verifyLogin()
{
mPrefs = getPreferences(MODE_PRIVATE);
String accessToken = mPrefs.getString("access_token", null);
facebook.setAccessToken(accessToken);
long expires = mPrefs.getLong("access_expires", 0);
if (accessToken != null)
{
facebook.setAccessToken(accessToken);
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
facebook.authorize(this, new String[] {
"email", "publish_stream", "create_event"
}, 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", 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
}
});
}
}
}

Facebook api not working in my emulator?

I have implemented login with facebook in my project.
The code is below:
public class login extends Activity{
ImageView fbtn;
private SharedPreferences mPrefs;
static Facebook facebook = new Facebook("271089732997803");
String access_token;
long expires;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yf_login1);
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
fbtn = (ImageView)findViewById(R.id.fbtn);
fbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(access_token != null) {
facebook.setAccessToken(access_token);
Log.v("access_token", access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
Log.i("expires", ""+expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(login.this,new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
else{
startActivity(new Intent(login.this,ChooseTeam.class));
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
Now my question is when i click on the the fb button it will load the progress bar and after 30-40 second it returns the same page.
The most important thing is when i run the same project in my another pc it will run perfectly, opens the dialog of login for the facebook and got the value in my preferences. But in my case i cannot even get the preferences made in my data.
What will be the problem in my emulator?? I am using eclipse galilio and sdk20.
I got the solution actually my antivirus is blocked the internet for the emulator. So i have uninstalled the antivirus and run the app and it works.
Thank you all for helping me out.
Try this....
and use this Permission for Share in Facebook..
private String[] mPermissions={"publish_stream"};
mFb.authorize(SettingActivity.this, mPermissions,new com.fbintegration.Facebook.DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
SessionStore.save(mFb, getApplicationContext());
}
public void onCancel()
{
// TODO Auto-generated method stub
}
});
and this is Facebook Connector Class....
public class FacebookConnector
{
private Facebook facebook = null;
private Context context;
private String[] permissions;
private Handler mHandler;
private Activity activity;
//private SessionListener mSessionListener = new SessionListener();;
public FacebookConnector(String appId,Activity activity,Context context,String[] permissions)
{
this.facebook = new Facebook(appId);
SessionStore.restore(facebook, context);
this.context=context;
this.permissions=permissions;
this.mHandler = new Handler();
this.activity=activity;
}
public void login()
{
if (!facebook.isSessionValid())
{
facebook.authorize(this.activity, this.permissions,new LoginDialogListener());
}
}
/*public void logout()
{
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}*/
public void postMessageOnWall(String msg)
{
if (facebook.isSessionValid())
{
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try
{
//JSONObject response=Util.parseJson(facebook.request("me/feed", parameters,"POST"));
String response = facebook.request("me/feed", parameters,"POST");
System.out.println(response);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
}
}
private final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
SessionEvents.onLoginSuccess();
}
public void onFacebookError(FacebookError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onError(DialogError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onCancel()
{
SessionEvents.onLoginError("Action Canceled");
}
}
private class SessionListener implements AuthListener, LogoutListener
{
public void onAuthSucceed()
{
SessionStore.save(facebook, context);
}
public void onAuthFail(String error) {
}
public void onLogoutBegin() {
}
public void onLogoutFinish() {
SessionStore.clear(context);
}
}
public Facebook getFacebook()
{
return this.facebook;
}
}

Calling new activity after facebook login | Android

I have 2 activities in my android application. On the first one, I ask the user to login with facebook. after the user logs in, i collect the user data such as email, name and call a new activity passing these parameters to it. below is my facebook authorize method:
public void loginFB(final View v)
{
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
this.getlogininfo(v);
}
private void getlogininfo(View v) {
// TODO Auto-generated method stub
logininfo(v);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
Below is my logininfo() method:
public void logininfo(final View v){
mAsyncRunner.request("me", new RequestListener(){
#Override
public void onComplete(String response, Object state) {
try{
Log.d("Profile", response.toString());
JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
Intent fbLogged = new Intent();
Bundle passData = new Bundle();
passData.putString("fname", fname1);
passData.putString("lname", lname1);
passData.putString("email", email);
fbLogged.putExtras(passData);
fbLogged.setClass(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
catch(JSONException e){
Log.w("This", "eror");
}
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
});
}
So, my new activity is starting on OnComplete() of getting the user data.
This works perfectly, but when the user clicks login, and logs in with facebook, the first activity page remains on the screen for a few seconds and then the next activity is called. there is a lag. How can I fix the lag? When the user clicks login and after the login is authorized, it should take the user to directly the second activity. Any suggestions?
Thanks!
It's simple, you are running the fb graph request in a new thread (using the AsyncRunner) but only when that request is completed you start the new activity and that's why you get that "lag".
You should run the graph request in the new activity instead of the first one, something like:
public void loginFB(final View v) {
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
Intent fbLogged = new Intent(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
public class RequestFb extend Activity {
protected void onCreate(Bundle savedInstanceState) {
Facebook facebook = new Facebook("YOUR_APP_ID");
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(facebook);
asyncRunner.request("me", new RequestListener(){
try {
final JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
runOnUiThread(new Runnable() {
public void run() {
// use the data
}
});
}
catch(JSONException e) {
Log.w("This", "eror");
}
});
}
}

Categories

Resources