在Android中从Facebook获取电子邮件ID

时间:2014-08-22 07:00:28

标签: android facebook-graph-api facebook-android-sdk

如何从facebook获取电子邮件ID。我从以下代码获得了所有其他信息,但我想获得用户电子邮件ID,但它不会检索用户电子邮件。

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_and_facebook);
    initializeViews();
    initializeOthers();
    setListners();
    setEditTextPostition();

}

private void setEditTextPostition() {
    // TODO Auto-generated method stub
    _etPassword.setPadding(60, 0, 0, 0);
    _etUserName.setPadding(60, 0, 0, 0);
}

private void initializeOthers() {
    // TODO Auto-generated method stub
    // facebook = new Facebook(APP_ID);
    // mAsyncRunner = new AsyncFacebookRunner(facebook);
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    fb_session = Session
            .openActiveSessionFromCache(getApplicationContext());

    _clinet = new DefaultHttpClient();
    _post = new HttpPost("http://appliconic.com/SG_Taxi/json.php");
    _pDialogue = new ProgressDialog(this);
}

private void setListners() {
    // TODO Auto-generated method stub
    _bFacebookLogin.setOnTouchListener(this);
    _bLogin.setOnTouchListener(this);
    _bSignUp.setOnTouchListener(this);

}

private void initializeViews() {
    // TODO Auto-generated method stub
    _etPassword = (EditText) findViewById(R.id.etPasswordLogin);
    _etUserName = (EditText) findViewById(R.id.etUserNameLogin);
    _bFacebookLogin = (Button) findViewById(R.id.bFacebookLogin);
    _bLogin = (Button) findViewById(R.id.bLogin);
    _bSignUp = (Button) findViewById(R.id.bRegisterLogin);
}

public class CheckDataBase extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        _pDialogue.setMessage("Please wait...");
        _pDialogue.setCancelable(false);
        _pDialogue.show();
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        ArrayList<NameValuePair> l_nameValuePairs = new ArrayList<NameValuePair>();
        l_nameValuePairs.add(new BasicNameValuePair("tag", "login"));
        l_nameValuePairs
                .add(new BasicNameValuePair("tag_type", "passenger"));
        l_nameValuePairs.add(new BasicNameValuePair("login", "account"));
        l_nameValuePairs.add(new BasicNameValuePair("txtb_email", ""
                + _etUserName.getText().toString().trim()));
        l_nameValuePairs.add(new BasicNameValuePair("txtb_password", ""
                + _etPassword.getText().toString().trim()));
        try {
            _post.setEntity(new UrlEncodedFormEntity(l_nameValuePairs));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpResponse l_response = null;
        try {
            l_response = _clinet.execute(_post);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int status = l_response.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity e = l_response.getEntity();
            String l_data = null;
            try {
                l_data = EntityUtils.toString(e);
            } catch (org.apache.http.ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            JSONObject l_jsonObject = null;
            try {
                l_jsonObject = new JSONObject(l_data);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            return l_jsonObject;
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub

        if (_pDialogue.isShowing()) {
            _pDialogue.dismiss();
        }
        String l_successMsg = null;
        String l_errorMsg = null;
        try {
            l_successMsg = result.getString("success_msg");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            l_errorMsg = result.getString("error_msg");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (l_errorMsg == null) {
            Toast.makeText(getApplicationContext(), "" + l_successMsg,
                    Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(),
                    ActivityNearDriverMap.class));
        } else if (l_errorMsg.compareTo("YOU ARE ALREADY LOGGED IN") == 0) {
            startActivity(new Intent(getApplicationContext(),
                    ActivityNearDriverMap.class));
        } else {
            Toast.makeText(getApplicationContext(), "" + l_errorMsg,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    new AlertDialog.Builder(this).setMessage("Do you want to Exit ? ")
            .setPositiveButton("Ok", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    finish();
                }
            }).setNegativeButton("Cancel", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            }).setCancelable(false).show();
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bFacebookLogin:
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:

            if (fb_session != null && fb_session.isOpened()) {

                makeMeRequest(fb_session);
                Log.i("Facebook Login State == >", "Facebook Login State");
            } else {
                if (fb_session == null) {
                    fb_session = new Session(getApplicationContext());
                }
                Session.setActiveSession(fb_session);
                ConnectToFacebook();
                Log.i("Facebook not Login State == >",
                        "Facebook Not login State");
            }

            // facebookLogin();

            break;
        case MotionEvent.ACTION_UP:
            break;
        }
        break;
    case R.id.bLogin:
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (_etUserName.getText().toString().compareTo("") != 0
                    && _etPassword.getText().toString().compareTo("") != 0) {
                _singletonObj.SetEmail(_etUserName.getText().toString()
                        .trim());
                new CheckDataBase().execute("");
            } else {
                Toast.makeText(getApplicationContext(),
                        "Enter Info Properly", Toast.LENGTH_SHORT).show();
            }
            break;
        case MotionEvent.ACTION_UP:
            break;
        }
        break;
    case R.id.bRegisterLogin:
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startActivity(new Intent(getApplicationContext(),
                    ActivityRegistrationForm.class));
            break;
        case MotionEvent.ACTION_UP:
            break;
        }
        break;
    }
    return true;
}

private void makeMeRequest(final Session session) {

    Request request = Request.newMeRequest(session,
            new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // TODO Auto-generated method stub
                    try {

                        if (user != null) {
                            String firstName = user.getFirstName();
                            String lastName = user.getLastName();
                            String id = user.getId();

                            //String Birth=user.getBirthday();

                            Log.e("facebookid", id);
                            Log.e("firstName", firstName);
                            Log.e("lastName", lastName);
                            //Log.e("Birthday",Birth);
                            Log.i("Nain",
                                    "Email " + user.getProperty("email").toString());
                            Log.i("Response", response.toString());
                            // Toast.makeText(getApplicationContext(), name
                            // +FirstName+Email,Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
    request.executeAsync();
}

private void ConnectToFacebook() {

    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        Log.i("ConnectToFacebook  if == >", "ConnectToFacebook if");
        OpenRequest newSession = new Session.OpenRequest(this);
        newSession.setCallback(callback);
        session.openForRead(newSession);

        try {
            Session.OpenRequest request = new Session.OpenRequest(this);
            request.setPermissions(Arrays.asList("basic_info","email"));


        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Log.i("ConnectToFacebook  else == >", "ConnectToFacebook else");
        Session.openActiveSession(this, true, callback);
    }
}

private Session.StatusCallback callback = new Session.StatusCallback() {
    public void call(final Session session, final SessionState state,
            final Exception exception) {
        onSessionStateChange(session, state, exception);

    }
};

private void onSessionStateChange(final Session session,
        SessionState state, Exception exception) {
    if (session != null && session.isOpened()) {
        makeMeRequest(session);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Session.getActiveSession().onActivityResult(this, requestCode,
            resultCode, data);
}

}

问题出在电子邮件中我收到了其他信息但是因电子邮件而变为空。

0 个答案:

没有答案