android how to add permission to facebook - android

i want to add permission to read email from the facebook android sdk.
code
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
et_firstName.setText(user
.getFirstName());
et_lastName.setText(user
.getLastName());
Log.e("data",
user.asMap().get("email")
+ "");
URL image_value;
try {
image_value = new URL(
"http://graph.facebook.com/"
+ user.getId()
+ "/picture");
iv_profileImage
.setImageBitmap(BitmapFactory
.decodeStream(image_value
.openConnection()
.getInputStream()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
});
}
}
});
what i have tried
I read a lot that this can be done using loginbutton but i don't want to use loginbutton.
also i read that if i don't want to use logingbutton, i have to use openfor session, but i didn't know how to use that
please help me, i have been trying for it for like a week

If you use a LoginButton, use:
loginButton.setReadPermissions(Arrays.asList("email"));
If you start the Session yourself, use:
session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));
requests/permissions helpfull link: https://developers.facebook.com/tools/explorer/
After successfull login, try the request again including the email field.

Related

How post message on facebook without open any dialog?

I want to post messages on facebook without open dialog using native Facebook android app.
I am using facebook sdk 3.5.2.
I have successfully post messages on wall.
I am facing some problems.
1) if I logout from native Facebook app. Then it post messages to previous user's Facebook wall & it not ask for authentication.
2)If user login with different account in Facebook native app, it still post messages to
previous account( which login first time through app). Not ask for authentication.
Code:-
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
new messagePostAsyn().execute(session);
}
}
});
Method:
private void postStatus(final Session session, String message) {
Bundle _postParameter = new Bundle();
_postParameter.putString("name", message);
_postParameter.putByteArray("picture", bytes);
_postParameter.putString("caption", "To help....");
_postParameter.putString("description", "Testing...");
Request request = new Request(session, "me/photos", _postParameter,
HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
System.out.println("response......" + response);
}
});
Request.executeBatchAsync(request);
}
This method used in messagePostAsyn() class.
Try this Code :
public void postToWall(String message) {
Bundle params = new Bundle();
params.putString("message", message);
// Uses the Facebook Graph API
try {
facebook.request("/me/feed", params, "POST");
this.finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Android Facebook native app not getting user email and birthday even with permissions set and correct information in fields

I'm trying to get the user email and birthday (using a Me request). My app has email and user_birthday permissions and the fb account i'm using has an email and a birthday set.
When I try using the 'Graph API Explorer' (https://developers.facebook.com/tools/explorer) using the user access_token with 'fields=id,email,birthday' all I get is the id.
Can anybody advice me on this please.
Here is my code:
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// here I check the infos I got.
Log.d("some tag", user.getInnerJSONObject().toString()); // it shows only the id, no email or birthday.
if (Session.getActiveSession() != null) {
Log.i(TAG, "Log out from FB");
Session.getActiveSession().closeAndClearTokenInformation();
}
}
}
});
// set params.
request.getParameters().putString("fields", "id,email,birthday");
// execute request.
request.executeAsync();
Log.d(TAG, request.toString());
}
if (exception != null) {
exception.printStackTrace();
}
}
});
Many thanks.
I finally changed the approach using the OpenRequest instead of getMeRequest:
Here is my code:
public void onClick(View v) {
Logger.d(TAG, "Start FB session");
// check if a session exists.
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
// create a new session.
Session session = new Session.Builder(getApplicationContext()).build();
// set it a the active session.
Session.setActiveSession(session);
// keep a variable link to session.
currentSession = session;
}
// if a session is already open then issue a request using the available
// session. Otherwise ask for user credentials.
if (currentSession.isOpened()) {
// The user is logged in.
Logger.e(TAG, "User is logged in.");
Session.getActiveSession().closeAndClearTokenInformation();
Logger.i(TAG, "Session closed an token information cleared.");
// get user data here with no extra call.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
} else {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) this);
// don't use SSO.
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
// no callback needed.
op.setCallback(null);
// set permissions.
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
// open session for read.
currentSession.openForRead(op);
Logger.d(TAG, "Session open for read request issued.");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG, "Request code is: " + requestCode);
Logger.d(TAG, "Result code is: " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getApplicationContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
}
}
I hope this helps.
When you are using Request.GraphUserCallback(), its best to use it in MAIN UI THREAD
Session s = Session.getActiveSession();
if(s!=null)
{
Request.executeMeRequestAsync(s,new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user!=null)
{
try {
String fbid=null;
String birthday=null;
fbid=user.getId();
birthday=user.getBirthday();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
});
}
you can try this also before the Request.executeMeRequestAsync(...){...}
List<String> permissions = session.getPermissions();
List<String> permissionsBirthday = new ArrayList<String>();
permissionsBirthday.add("user_birthday");
if (!isSubsetOf(permissionsBirthday, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, permissionsBirthday);
if (setPermissions(session, newPermissionsRequest))
return;
}
the method isSubsetOf();
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
hope this helps.
This code worked for me hope you find it useful. This retrieves the user email in 3 different ways and also logs it
try{
// new Read().execute("Facebook");
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// TextView welcome = (TextView) findViewById(R.id.welcome);
// welcome.setText("Hello " + user.getName() + "!");
Log.d("useremai", (String) user.getProperty("email"));
Log.d("USER", user.getInnerJSONObject().toString());
JSONObject details = user.getInnerJSONObject();
useremail = details.optString("email");
Log.d("name", user.getName());
Log.d("email", useremail);
}
}
});
}
}
});
}catch(NoClassDefFoundError e){
e.printStackTrace();
}
Try this one:
if you have object of user than do below:
if (user != null) {
String UserId = user.getId();
try {
Log.i("Birthdate", ""+user.getInnerJSONObject().getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
}
}

android facebook how to add permission

I want to add permission to get the email of the user, i am using this code
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
et_firstName.setText(user
.getFirstName());
et_lastName.setText(user
.getLastName());
Log.e("email",
user.asMap().get("email")
+ "");
} else {
}
}
});
}
}
});
break;
I have tried googleing alot alot but all they talk about loginbutton but i don't want to use loginbutton,
any help would be appreciated
Download SDK http://developers.facebook.com/android/ and read docs...

Facebook Login not working

Hi I have used facebook login in my android app. It works fine when I build and run it in my device.
Now I uploaded the app to playstore and published it for beta testing. But not the facebook login is not working. I guess the session is not getting opened somehow. I deleted the app and then reinstalled from eclipse. Then its working fine. I am not able to debug as I don't know how to debug a signed release build. Or I guess its not possible. Anyways any similar issues to this happened to you?
Any work around? Or how to debug?
I am using the Facebook Login button and the rest of the code is below
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
if(!PreferenceHelper.getString(this, "logged_in_status").equals("YES")){
Log.i("sdf", "Logged in...");
this.progress.setVisibility(View.VISIBLE);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
userInfo = user;
userId = user.getId();
user_name = user.getName();
Handler looper = new Handler(Looper.getMainLooper());
looper.post(new Runnable() {
#Override
public void run() {
new DownloadFile().execute("http://graph.facebook.com/"+userId+"/picture?type=large");
}
});
try {
emailText = user.getInnerJSONObject().getString("email");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
}
});
}
else{
this.shareFacebook.setVisibility(View.VISIBLE);
}
} else if (state.isClosed()) {
PreferenceHelper.setString(this, "logged_in_status", "NO");
PreferenceHelper.setString(this, "facebook_user_id", "");
PreferenceHelper.setString(this, "user_id","");
PreferenceHelper.setString(this, "user_name", "");
Intent a = new Intent(this,MainMenuActivity.class);
startActivity(a);
overridePendingTransition (R.anim.right_slide_in, R.anim.left_slide_out);
Log.i("sdf", "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
Thanks and Regards,
android error with facebook login on market
The above post explains it all. The keyhash is different for debug and release versions! :)

Getting email address by using Facebook SDK 3.0.1 for Android

I'm currently developing an application which aims to authenticate any user by using Facebook acoount.
I have a trouble in getting user email from user's account. My code is below
private void signInWithFacebook() {
SessionTracker mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(getBaseContext());
Session mCurrentSession = mSessionTracker.getSession();
if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
Session.setActiveSession(session);
mCurrentSession = session;
}
if (!mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(FacebookLoginActivity.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
}
}else {
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getLink() + " "+ response);
}
});
}
}
I am using Facebook SDK 3.0.1 for Android.
I have set the permissions required by the Facebook Graph Api.
In the response xml, there is no such field like email.
Facebook Sdk documentations are not good enough and I don't know hot to obtain email address.
Thanks in advance.
Email is not a default field that's returned. Instead, you should create a meRequest, and pass it a parameter like: fields=email.
Request me = Request.newMeRequest(mCurrentSession, new GraphRequestCallback() {...});
Bundle params = me.getParameters();
params.putString("fields", "email,name");
me.setParameters(params);
me.executeAsync();
you call just like this under regular things - only different you cannot directly user.email
System.out.println(user.asMap().get("email").toString());
regular :
#Override
public void onClick(View v) {
// start Facebook Login
Session.openActiveSession(Giris.this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
System.out.println(user.getName());
System.out.println(user.getBirthday());
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
System.out.println(user.getLink());
System.out.println(user.getUsername());
System.out.println(user.getLocation());
System.out.println("facebook user id" + user.getId());
System.out.println(user.asMap().get("email").toString());
// Session.OpenRequest open = new Session.OpenRequest(Login)
}
}
});
}
}
});
}
just call this method will return user email id to you.
private void doSocialNetworkinWithFacebook()
{
// check for session
Session session=Session.getActiveSession();
if (session != null && session.isOpened())
{
// user is already login show
try
{
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email", "publish_actions"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
Toast.makeText(activity, "Welcome "+user.getName(), Toast.LENGTH_SHORT).show();
// publishFeedDialog(session);
try
{
strFirstName = user.getFirstName().toString();
strLocation = user.getLocation().getProperty("name").toString();
strEmail = user.asMap().get("email").toString();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
strEmail="";
}
runOnUiThread(new Runnable()
{
public void run()
{
setUserInfoFromFacebook(strFirstName, strLocation, strEmail);
}
});
}
}
});
}
else
{
// user is not log in
//show login screen
// start Facebook Login
try
{
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email", "publish_actions"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Session.openActiveSession(activity, true, new Session.StatusCallback()
{
// callback when session changes state
#Override
public void call(final Session session, SessionState state, Exception exception)
{
//session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));
Log.d(TAG, "Session :"+session.toString());
Log.d(TAG, "Session is opened :"+session.isOpened());
if (session.isOpened())
{
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
Toast.makeText(activity, "Welcome "+user.getName(), Toast.LENGTH_SHORT).show();
// publishFeedDialog(session);
try
{
strFirstName = user.getFirstName().toString();
strLocation = user.getLocation().getProperty("name").toString();
strEmail = user.asMap().get("email").toString();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
strEmail="";
}
runOnUiThread(new Runnable()
{
public void run()
{
setUserInfoFromFacebook(strFirstName, strLocation, strEmail);
}
});
}
}
});
}
else if(session.isClosed())
{
Toast.makeText(activity, "Unable to connect facebook, please try later..",Toast.LENGTH_SHORT).show();
}
}
});
}
}
First add the appropriate permission, then fetch the email using the getProperty function.
permissions = Arrays.asList("email","languages","user_location","user_likes", "user_education_history","user_work_history","user_hometown","user_about_me","user_status");
Log.i(TAG, "user_email : " + user.getProperty("email"));

Categories

Resources