10

Here is my code realising the connection.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class FacebookConnect extends Activity{

    public static final String TAG = "FACEBOOK";
    private Facebook mFacebook;
    public static final String APP_ID = "XXX";
    private AsyncFacebookRunner mAsyncRunner;
    private static final String[] PERMS = new String[] { "read_stream" };
        private SharedPreferences sharedPrefs;
        private Context mContext; 

        private TextView username;
        private ProgressBar pb;
        String fbId, fbName, fbEmail;

        public void setConnection() {
                mContext = this;
                mFacebook = new Facebook(APP_ID);
                mAsyncRunner = new AsyncFacebookRunner(mFacebook);
        }

        public void getID(TextView txtUserName, ProgressBar progbar) {
                username = txtUserName;
                pb = progbar;
                if (isSession()) {
                        Log.d(TAG, "sessionValid");
                        mAsyncRunner.request("me", new IDRequestListener());
                } else {
                    // no logged in, so relogin
                    Log.d(TAG, "sessionNOTValid, relogin");
                        mFacebook.authorize(this, PERMS, new LoginDialogListener());
                }
        }

        public boolean isSession() {
                sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
                String access_token = sharedPrefs.getString("access_token", "x");
            Long expires = sharedPrefs.getLong("access_expires", -1);
                Log.d(TAG, access_token);

                if (access_token != null && expires != -1) {
                        mFacebook.setAccessToken(access_token);
                        mFacebook.setAccessExpires(expires);
                }
                return mFacebook.isSessionValid();
        }

        private class LoginDialogListener implements DialogListener {

                @Override
                public void onComplete(Bundle values) {
                        Log.d(TAG, "LoginONComplete");
                    String token = mFacebook.getAccessToken();
                    long token_expires = mFacebook.getAccessExpires();
                    Log.d(TAG, "AccessToken: " + token);
                    Log.d(TAG, "AccessExpires: " + token_expires);
                    sharedPrefs = PreferenceManager
                                    .getDefaultSharedPreferences(mContext);
                    sharedPrefs.edit().putLong("access_expires", token_expires).commit();
                    sharedPrefs.edit().putString("access_token", token).commit();
                    mAsyncRunner.request("me", new IDRequestListener());
                }

                @Override
                public void onFacebookError(FacebookError e) {
                        Log.d(TAG, "FacebookError: " + e.getMessage());
                }

                @Override
                public void onError(DialogError e) {
                        Log.d(TAG, "Error: " + e.getMessage());
                }

                @Override
                public void onCancel() {
                        Log.d(TAG, "OnCancel");
                }
        }

        private class IDRequestListener implements RequestListener {

                @Override
                public void onComplete(String response, Object state) {
                        try {
                                Log.d(TAG, "IDRequestONComplete");
                            Log.d(TAG, "Response: " + response.toString());
                                JSONObject json = Util.parseJson(response);
                                fbId = json.getString("id");
                                fbName = json.getString("name");
                                //fbEmail = json.getString("email");

                                FacebookConnect.this.runOnUiThread(new Runnable() {
                                    public void run() {
                                    username.setText("Welcome: " + name + "\n ID: " + fbId);
                                pb.setVisibility(ProgressBar.GONE);
                                    }
                            });
                        } catch (JSONException e) {
                                Log.d(TAG, "JSONException: " + e.getMessage());
                    } catch (FacebookError e) {
                            Log.d(TAG, "FacebookError: " + e.getMessage());
                        }
                }

                @Override
                public void onIOException(IOException e, Object state) {
                        Log.d(TAG, "IOException: " + e.getMessage());
                }

                @Override
                public void onFileNotFoundException(FileNotFoundException e,
                                Object state) {
                        Log.d(TAG, "FileNotFoundException: " + e.getMessage());
                }

                @Override
                public void onMalformedURLException(MalformedURLException e,
                                Object state) {
                        Log.d(TAG, "MalformedURLException: " + e.getMessage());
                }

                @Override
                public void onFacebookError(FacebookError e, Object state) {
                        Log.d(TAG, "FacebookError: " + e.getMessage());
                }

        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                mFacebook.authorizeCallback(requestCode, resultCode, data);
        }
}

As a response I get a JSON. Example:

08-15 14:22:42.160: DEBUG/FACEBOOK(1258): Response: {"id":"3159628280","name":"Peter Black","first_name":"Peter","last_name":"Black","link":"http:\/\/www.facebook.com\/Peter.Black","username":"Peter.Black","gender":"male","timezone":3,"locale":"bg_BG","verified":true,"updated_time":"2011-08-14T08:42:59+0000"}

My question is how can I get the user's email (the email with which he logs into Facebook)?

Stefan Doychev
  • 711
  • 3
  • 12
  • 30

4 Answers4

10

You need the email permission to read the users email adress. That will add a email tag in your json-response from [uid] or me requests.

email

Provides access to the user's primary email address in the email property. Do not spam users. Your use of email must comply both with Facebook policies and with the CAN-SPAM Act.

Source: Permissions

1

Do it when you are clicking Login button:

  OpenRequest openRequest = new OpenRequest(this);
  List<String> readPermissions = new ArrayList<String>();
  readPermissions.add("email");
  openRequest.setPermissions(readPermissions);
  openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
  openRequest.setCallback(statusCallback);
  session.openForRead(openRequest);
HemChe
  • 2,249
  • 1
  • 21
  • 33
1

Another option to retrieve email in Facebook SDK 3.0.x is by using this open source library:

android-simple-facebook
https://github.com/sromku/android-simple-facebook

  • First, use this permission

    Permissions.EMAIL
    
  • Then, login

    mSimpleFacebook.login(MainActivity.this);
    
  • And then, get the profile

    mSimpleFacebook.getProfile(new OnProfileRequestAdapter()
    {
        @Override
        public void onComplete(Profile profile)
        {
            String id = profile.getId();
            String firstName = profile.getFirstName();
            String birthday = profile.getBirthday();
            String email = profile.getEmail();
            String bio = profile.getBio();
            // ... and many more properties of profile ...
        }
    });
    

Full examples are explained here including permissions stuff and other simplified methods (like: publish feeds, get friends and more...)

sromku
  • 4,663
  • 1
  • 36
  • 37
1

Before calling Session.openActiveSession do this to get permissions add this:

List<String> permissions = new ArrayList<String>();
permissions.add("email");

The last parameter in Session.openActiveSession() should be permissions. Now you can access user.getProperty("email").toString().

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Ramkailash
  • 1,852
  • 1
  • 23
  • 19