How to get the Facebook Friendlist using Intent in Android? - android

I would like to get the friendlist of the facebook using intent.
Please let me know if there is any way to get the friends list of the facebook by using built in application of the device.
Thanks.

You need to integrate the Android SDK into your app, here is the link to download the latest SDK. You then will have to have the user authenticate your app to access their information.
Here is sample code to do this
private SessionTracker mSessionTracker;
private Session mCurrentSession;
private void signInWithFacebook() {
mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(getBaseContext());
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(SignUpChoices.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);
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
}
});
}
}
}
One you have a user that has approved your app you can perform other Request about their information. friends info example

Finally i found a way to get the friendlist of the Facebook using Intent.
Intent m_fb=getOpenFacebookIntent(m_context);
startActivity(m_fb);
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW,Uri.parse("fb://profile/<user_id>/fans"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/abc.xyz"));
}
}
You can use Official Facebook App with Intent listed HERE.

Related

Fb not providing Login info to users that are not listed in app's role as admin or tester

I have a confusable situation here. In my android app, I am using Fb login and SDK.Things work fine when fb native app is not present.But when fb app is there and login is done then FB provides info only when I logged on with native FB app and not when somebody else logins. The screen just flashes once and goes away. I have also found that roles that are listed in app on fb including me (admin) & testers are able to fetch information, but not the other normal users. I have tried but I dont know where the fault is happening?
thanks.
public void signInWithFacebook() {
Constant.printKeyHash(MainActivity.this);
mSessionTracker = new SessionTracker(mContext, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(mContext);
Constant.mCurrentSession = mSessionTracker.getSession();
if (Constant.mCurrentSession == null || Constant.mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
} else {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
}
if (!Constant.mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest((Activity) mContext);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location", "user_friends"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
Constant.mCurrentSession.openForRead(openRequest);
try {
// progressfb.show();
// progressfb.setCancelable(false);
}
catch (Exception e)
{
}
accessFacebookUserInfo();
}
} else {
// progressfb.show();
accessFacebookUserInfo();
}
}
public void accessFacebookUserInfo() {
if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()) {
Bundle bundle = new Bundle();
bundle.putString("fields", "picture,email,first_name, last_name, name");
// bundle.putString("fields", "email");
// bundle.putString("fields", "first_name");
final Request request = new Request(Session.getActiveSession(), "me", bundle, HttpMethod.GET, new Request.Callback() {
#SuppressWarnings("unused")
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject = graphObject.getInnerJSONObject();
Log.i("", "faacebook response===" + jsonObject.toString());
String facebook_id = jsonObject.getString("id");
JSONObject picture_obj = jsonObject.getJSONObject("picture");
JSONObject picture_data = picture_obj.getJSONObject("data");
// fb_pic_url = picture_data.getString("url");
String first_name = jsonObject.getString("name");
String last_name = jsonObject.getString("last_name");
String socialName = jsonObject.getString("name");
eemail = jsonObject.getString("email");
String fb_pic_url = "https://graph.facebook.com/"
+ facebook_id
+ "/picture?type=large";
new fbSigninActivity().execute(eemail,first_name);
callFacebookLogout(MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "something went wrong", Toast.LENGTH_LONG).show();
}
}
}
});
Request.executeBatchAsync(request);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// com.facebook.Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Constant.mCurrentSession.isOpened()) {
accessFacebookUserInfo();
} else {
//Utils.showCenterToast(contxt, getResources().getString(R.string.msg_went_wrong));
}
} else {
Constant.mCurrentSession = null;
mSessionTracker.setSession(null);
// progressfb.dismiss();
}
}
The issue is happening because the feature you are trying to use needs to be approved by Facebook first. You must submit an APK for them to test. Anyone listed as an Admin, Developer, or Tester of your app should work fine (you may need to add their debug hash of the device to the list). But until your app gets approved by Facebook to use specific features or Graph Calls normal users will NOT be able to use it.

Why I get null for user friend's birthday in android app that use facebook api?

I write this code in my android app i can get the user friends name but i cannot get their birthday what should I do?I think that I have problem with permissions but I don;t know where.
Session s = new Session(this);
Session.setActiveSession(s);
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("friends_birthday","user_friends","public_profile"));
request.setCallback( new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request myFriendsRequest = Request.newMyFriendsRequest(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
for (GraphUser user : users) {
// Here I can get the friend name
welcome.setText(welcome.getText() + "Hello " + user.getName() + "!");
// But here I cannot get birthday and it returns null
Toast.makeText(MyContext, user.getBirthday(), Toast.LENGTH_SHORT).show();
}
}
}
});
Bundle requestParams = myFriendsRequest.getParameters();
requestParams.putString("fields", "name,birthday");
myFriendsRequest.setParameters(requestParams);
myFriendsRequest.executeAsync();
}
}
});
s.openForRead(request);
That's because all friends_* permissions have been removed with Graph AP v2.0. You can't access their data anymore, except name and profile picture.
See
https://developers.facebook.com/docs/apps/changelog#v2_0_permissions

Android FacebookSDK get Birthday

I have created sample app with facebook sdk integration. Now I can Login with facebook Also get some basic information from facebook. But fail to got birthday from "GraphUser" I have noticed that for birthday I need to set permission "user_birthday" which I have already set. I couldn't get what wrong with response.
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
private void startFacebookLogin() {
openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
//make request to the /me API
Log.e("sessionOpened", "true");
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String id = user.getId();
String email = user.getProperty("email").toString();
Log.d("AllData", user.toString());
Log.e("facebookId", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
String Birthdate=user.getBirthday();
Log.e("Birthdate", Birthdate+"::Birthdate");
}
}
}).executeAsync();
}
}
}, Arrays.asList(
new String[] { "email", "user_location", "user_birthday","user_likes" }));
}
GraphUser respose is
GraphObject{graphObjectClass=GraphUser, state={"id":"…..","first_name":"…..","timezone":5.5,"email":"…..#gmail.com","verified":false,"name":"…..","locale":"en_US","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/....\/","last_name":"…..","gender":"male","updated_time":"2012-12-21T06:54:19+0000"}}
Are you trying this with an admin/tester/developer user of your Facebook app? If not, the reason is that if you request extended permissions, you'll need to get your app through the Facebook app review process, as described here:
https://developers.facebook.com/docs/apps/review/login#do-you-need-review

Graph User returning Null, even though the session is created

I have been trying to integrate facebook to my app, but it always returns a Null Graph user.I tried adding the onActivityResult method as a solution told here, but still doesn't seem to help.
public class FacebookRegistartionActivity extends FragmentActivity
{
private Session.StatusCallback mStatusCallback = new SessionStatusCallback();
// private static final int REQUEST_CODE_SIGN_IN = 1;
Session session;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
fbRegistration();
}
public void fbRegistration() {
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
session = Session.getActiveSession();
Log.i("", "Session before : "+session);
if (session == null) {
session = new Session(FacebookRegistartionActivity.this);
if (session != null) {
Session.setActiveSession(session);
if (session != null && !session.isOpened()&& !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(mStatusCallback));
} else {
}
}
} else {
Log.i("", "Session null ... : "+session);
// start Facebook Login
Session.openActiveSession(this, true, mStatusCallback);
}
}
The code doesn't even reach the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.i("", "requestCode : "+requestCode);
Log.i("", "resultCode : "+resultCode);
Log.i("", "data : "+data);
if (resultCode == RESULT_OK) {
Session.getActiveSession().onActivityResult(this, requestCode,resultCode, data);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
Log.i("", "session in on status call back....."+session);
// Here the session is there, not null
if (session.isOpened()) {
Log.i("", "session is opened....."+session.isOpened());
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(final GraphUser user, Response response) {
Log.i("in SignUp", "USER :: " + user);
// Log.i("in SignUp", "response :: " + response);
if (user != null) {
try{
String fqlQuery = "select url from profile_pic where id=me() and width=200 and height=200";
Bundle params1 = new Bundle();
params1.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session, "/fql", params1,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
String serverresponse=response.getGraphObject().getInnerJSONObject().toString();
Log.e("serverresponse", ""+serverresponse);
JSONObject jsonobj=new JSONObject(serverresponse);
JSONArray array=jsonobj.getJSONArray("data");
Log.e("","data object : "+array);
jsonobj = array.getJSONObject(0);
String fbUserImageUrl = jsonobj.getString("url");
Log.e("","image url : "+fbUserImageUrl);
Logger.show(Log.INFO, "", " AccessToken with publish stream:: " +Session.getActiveSession().getAccessToken());
String uniqueId = user.getId();
String userName = user.getName();
String image = fbUserImageUrl; //"http://graph.facebook.com/"+user.getId()+"/picture?type=large";
String emailId = user.asMap().get("email").toString();
Logger.show(Log.INFO,"","uniqueId :: "+ uniqueId);
Logger.show(Log.INFO,"","userName :: "+ userName);
Logger.show(Log.INFO,"","image :: "+ image);
Logger.show(Log.INFO,"","emailId :: "+ emailId);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
else
{
Log.i("", "Graph user null");
// Always the Graph user is returning Null
}
}
}).executeAsync();
}
else
{
Log.i("", "Session not opened still.....");
}
}
}
}
EDIT :
I checked for answers, then realized, I just missed to add the permissions into the Android Manifest file.
Just realized! I Did everything except adding the following permission in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
But, Still wonder how I was able to get the session. Means, it does not require a net connection? Taken in to account that the device I tested had the facebook app installed in it.
Is the session provided by the facebook app, instead? Wished to know how the facebook app works in the login flow in our app, using the facebook sdk.
Any help regarding this is appreciated.
As I have mentioned in comment - Yes it is true that when a facebook Session object is created, it attempts to initialize itself from a TokenCachingStrategy. But there must be a Session token cache. As you have told that you were using same app id from some other app, the app was authorized by the user and the session was created and saved in the cache.
Because facebook manages session based on the app id and as the session was already created it fetched it from cache for your new app. But for fetching graph user when you call Request.newMeRequest, it is making an internet connection, since the internet permission was not there in the manifest, your app was not able to connect to facebook server to fetch the same.

how to get email id from facebook sdk in android applications?

I integrated Facebook login in my android application. I want to get email id of login user. How will I get it?
private void loginToFacebook() {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG, "Access Token" + session.getAccessToken());
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
userID =user.getId();
provider="facebook";
userName=user.getUsername();
firstName=user.getFirstName();
lastName=user.getLastName();
Log.d("****User****", "details:" + user);
}catch(Exception e){
Here is my code. i use Request.GraphUserCallback() method but there is no response of email from this method.
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().
EDIT:
This is the way I am doing facebook authorization:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
loginProgress.setVisibility(View.VISIBLE);
//start Facebook session
openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
//make request to the /me API
Log.e("sessionopened", "true");
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String id = user.getId();
String email = user.getProperty("email").toString();
Log.e("facebookid", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
}
}
});
}
}
}, permissions);
Add this method to your activity:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
Following the suggestion of Egor N, I change my old code
Session.openActiveSession(this, true, statusCallback);
whith this new one:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
Session.openActiveSession(this, true, permissions, statusCallback);
Now FB ask the user about the permission of email and I can read it in the response.
Try this article. Hope your issues will be solved Click Here
Btw, You need to use user.asMap().get("email").toString()); for receving the User Email ID.
Also, you need to assign that into some of label like lblEmail.setText where lblEmail is a Textview.

Categories

Resources