Can not access Facebook friends via Android application - android

I have a problem with accessing the graph API through my android application that retrieves a user's friends as JSONObject, extracts their names and displays them on the screen. It is supposed to be a simple and straightforward task but apparently it is not. When I run my application on Android Nexus I, I login to Facebook, then I am asked I click "Allow" button to grant permissions and I am redirected to a blank page. I am expect to see the name of my friends but it does not happen. Could some one assist me.
public class Login extends Activity
{
Facebook mFacebook = new Facebook("201509899926116");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
View linearLayout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = findViewById(R.id.main_layout);
/* Get existing access_token if any */
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null)
{
mFacebook.setAccessToken(access_token);
}
if(expires != 0)
{
mFacebook.setAccessExpires(expires);
}
/* Only call authorize if the access_token has expired. */
if(!mFacebook.isSessionValid())
{
mFacebook.authorize(this, new String[] {"user_birthday","email",
"user_relationships","user_religion_politics","user_hometown",
"user_location","user_relationship_details","user_education_history",
"user_likes","user_interests", "user_activities"},
new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", mFacebook.getAccessToken());
editor.putLong("access_expires", mFacebook.getAccessExpires());
editor.commit();
/* access the graph API */
Log.d("Facebook-Example-Friends Request", "Started API request");
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Log.d("Facebook-Example-Friends Request", "Finished API request");
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class FriendsRequestListener implements com.facebook.android.AsyncFacebookRunner.RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response)
{
try
{
// process the response here: executed in background thread
Log.d("Facebook-Example-Friends Request", "response.length(): " + response.length());
Log.d("Facebook-Example-Friends Request", "Response: " + response);
final JSONObject json = new JSONObject(response);
JSONArray d = json.getJSONArray("data");
int l = (d != null ? d.length() : 0);
Log.d("Facebook-Example-Friends Request", "d.length(): " + l);
for (int i=0; i<l; i++)
{
JSONObject o = d.getJSONObject(i);
String n = o.getString("name");
String id = o.getString("id");
TextView tv = new TextView(Login.this);
tv.setText(n);
((LinearLayout) linearLayout).addView(tv);
}
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
}
}
}

I think i might've found the issue.. According to the documentation on onComplet;
/**
* Called when a request completes with the given response.
*
* Executed by a background thread: do not update the UI in this method.
*/
And you are trying to update your UI, so addViews don't actually get reflected on the UI thread.. You should create a method in your activity that you can call from onComplete with runOnUIThread.. Something like this;
runOnUiThread(new Runnable() {
public void run() {
inserFacebookNames(facebookContactNames);
}
});
Let me know if this actually fixes it.. I'm curious if that was the reason..

Related

Facebook Login in Android application using Graph api

Anybody has working sample code for Facebook login in Android using the code snippet mentioned in Facebook developer site ??I couldn't understand it properly.I want to get the name and profile picture of logged in user.I want my app to display the name and profile picture as long as the session is active and need to modify the details if user changed any.
Currently what i do is,saving access token and name in shared preferences on first login and saving the image in sd card and checking access token value during each app launch.If access token value is not null,then i display the name from shared preferences and profile picture from sd card.I know that this is not the right way to do this.Somebody please help me with this.
You can this https://github.com/sromku/android-simple-facebook library it is pretty well defined and can get details of methods by searching simle facebook android on google. Do whatever you want to do with facebook with this library....happy coding
Try this code
public class LoginActivity extends Activity {
private Button butLogin, butMaps, butJackpot, butAdministrator, buttonMenu;
public static String APP_ID = " paste your app_id";
public static Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
public static SharedPreferences mPrefs;
private static final String TAG = "Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginToFacebook();
}
// Method to call the Facebook login
protected void loginToFacebook() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mPrefs = getSharedPreferences("faceBook", 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);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "public_profile",
"publish_stream" }, Facebook.FORCE_DIALOG_AUTH,
new DialogListener() {
#Override
public void onCancel() {
}
#Override
public void onComplete(Bundle values) {
getProfileInformation();
}
#Override
public void onError(DialogError error) {
}
#Override
public void onFacebookError(FacebookError fberror) {
}
});
} else {
getProfileInformation();
}
}
// FaceBook getting profile information
public void getProfileInformation() {
showLoadingImage();
Helper.setFacebookLogin(getApplicationContext(), true);
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
String json = response;
try {
Log.i("JSOB", json);
JSONObject profile = new JSONObject(json);
try {
Bitmap bmp = null;
URL image_value = new URL("http://graph.facebook.com/"
+ profile.getString("id")
+ "/picture?type=large");
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String first_name= profile.getString("first_name"));
String last_name=profile.getString("last_name"));
String email=profile.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
}
}
#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) {
}
});
}
// faceBook login method end
}

Unable to use facebook login in android device

I have same issue mentioned in this stack overflow question. But couldn't find the solution. My problem is when I use facebook login in my android device(which is not installed facebook app), my app works as expected. If I install the facebook application my code doesn't work anymore and It throws the error "Login failed. Please contact the maker of this app and ask them to report issue #1118578 to Facebook". My code is posted below
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "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",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
getProfileInformation();
} }); } }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
// getProfileInformation();
String arr[] = name.split(" ", 2);
String name1 = arr[0];
String name2 = arr[1];
Intent intent = new Intent(FacebookLogin.this, UserAccount.class);
/*Sending some arguments*/
Bundle bundle = new Bundle();
bundle.putString("UserName",name1);
bundle.putString("Id", email);
intent.putExtras(bundle);
logoutFromFacebook();
startActivity(intent); }
});
} catch (JSONException e) {
e.printStackTrace();
} } }); }
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
facebook.setAccessToken(null);
facebook.setAccessExpires(0);
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
} } }); }
}
Please anyone tell me how can I avoid this error...

Posting a photo on user's facebook wall

Below is my code and I integrated the facebook in my app. I am trying to make the user to be able to post an image on his wall after logging in. But I have been failing to make it for three days. Have seen few posts like this but I don't get any data(just it results in empty data data[]). I am even facing trouble with maintaining sessions too. Can some one please post working code or at least some sources where I can post image on facebook wall? Hope my below code is clear and my explanation is clear on what I have tried with the code below.
Activity's onCreate():-
public class FacebookActivity extends BaseActivity {
private static String APP_ID = "1303786178";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_screen);
btnFbLogin = (Button) findViewById(R.id.fbloginbtn);
btnFbLogout = (Button) findViewById(R.id.fblogoutbtn);
btnPostToWall = (Button) findViewById(R.id.fbpostbtn);
msget = (EditText)findViewById(R.id.fbmsget);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mHandler = new Handler();
String passedpath = getIntent().getStringExtra("imagepath").toString();
imageuri = Uri.parse(passedpath);
/**
* Login button Click event
* */
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();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//postToWall(imageuri);
getAlbumId();
}
});
}
Posting on Wall includes two functions in my code one is getAlbumId() and the other is posttowall() which will be called from getAlbumId():-
public void getAlbumId()
{
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
//String wallAlbumID = null;
mAsyncRunner.request("me/albums", new BaseRequestListener(){
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try{
Log.d("response in album"," "+response);
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
final String wallAlbumID = album.getString("id");
globalalbid = wallAlbumID;
Log.d("JSON", wallAlbumID);
break;
}
}
dialog.dismiss();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "id: " + globalalbid, Toast.LENGTH_LONG).show();
if(globalalbid != "")
postToWall(imageuri, globalalbid);
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
});
}
function to post on wall:
public void postToWall(Uri locuri, String wallid) {
if (facebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
// post on user's wall.
Uri photoUri = locuri;
if (photoUri != null) {
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e) {
e.printStackTrace();
}
String imagecaption = msget.getText().toString();
if(imagecaption != "")
params.putString("caption", imagecaption);
mAsyncRunner.request(wallid+"/photos", params, "POST", new PhotoUploadListener(), null);
} else {
Toast.makeText(getApplicationContext(),
"Error from the pic", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I always get album id empty. Is there anything wrong in the way that I try to get album id. Because I have seen on some posts those who try to access album id and then posting the image on album. They seem to be keeping wall as common findout in the album name. If it is so, some new ones contain timeline photos name, then how can we findout the album id. Please suggest.
Note: I want the image to be visible on to the wall not to only album.
Instead of uploading the photo to the user's album, post the image to /me/feed instead. Make sure you are asking the user for the publish_stream permission. This will upload the photo straight to the user's wall instead of going to an album.

Android facebook graph request

I am using android-facebook-sdk and i am trying to request profile information. But i cant get the response back. I have generated key hash with keytool and pasted it in the facebook app settings. Also i have added app ID in the code. Problem is that i cant get the profile information, or any information at all.
public class StartingPoint extends Activity {
Facebook facebook = new Facebook("actual app id");
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
Button btnt;
/*
* On Create
* */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* button Test
* */
btnt = (Button) findViewById(R.id.btntallinn);
btnt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/*
* Get existing access_token if any
*/
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);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email",
"publish_checkins", "rsvp_event", "manage_pages",
"publish_stream", "user_likes", "user_groups" },
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() {
}
});
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#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) {
}
});
}
}
Logcat:
03-22 09:38:13.545: D/Profile(23833): {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
03-22 09:38:13.545: W/System.err(23833): org.json.JSONException: No value for name
03-22 09:38:13.545: W/System.err(23833): at org.json.JSONObject.get(JSONObject.java:354)
03-22 09:38:13.545: W/System.err(23833): at org.json.JSONObject.getString(JSONObject.java:510)
03-22 09:38:13.545: W/System.err(23833): at com.tana.tallinn.tartu.StartingPoint$3.onComplete(StartingPoint.java:172)
03-22 09:38:13.545: W/System.err(23833): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:254)
Error says you don't have required access token. try to print facebook.getaccesstoken() and see if you have valid token.with this token you can try in browser to see if you get profile information

Trouble with accessing friends using Facebook-Android SDK

I have been struggling with android and the Facebook's graph API and I'm sure this is a piece of cake for intermediate programmers. What I want is a very simple Android application that logs in a user to Facebook, get the users consent to access information and finally to seamlessly query the graph API to get the users friends. I mention the work seamless because I have seen many sample applications that require the user to push a "get friends" button but I do not want that. I wish to extract the users friends without requiring him to push anything.
I have pasted the code below. I am able to to log-in and grant permission to my application. Next, I expect it to display my friends but it just directs me to a blank page. The problem might be that I am accessing the graph API in the wrong place because the Logcat does not contain the messages I print before and after the request. Could you please help me.
public class FacebookLogin extends Activity {
Facebook mFacebook = new Facebook("XXXXXXXXXXXX");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
View linearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = findViewById(R.id.main_layout);
mFacebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values)
{
Log.d("Facebook-Example-Friends Request", "Started API request");
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Log.d("Facebook-Example-Friends Request", "Finished API request");
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class FriendsRequestListener implements RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve, parse and display the JSON stream.
*/
public void onComplete(final String response)
{
Log.d("Facebook-Example-Friends Request", "FriendsListenerOnComplete");
try
{
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookLogin.this.runOnUiThread(new Runnable()
{
public void run()
{
int l = (friends != null ? friends.length() : 0);
for (int i=0; i<l; i++)
{
try
{
JSONObject o = friends.getJSONObject(i);
TextView tv = new TextView(FacebookLogin.this);
tv.setText(o.getString("name"));
((LinearLayout) linearLayout).addView(tv);
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), "JSON parsing error", Toast.LENGTH_LONG);
}
}
}
});
}
catch(JSONException e)
{
Log.d("Facebook-Example-Friends Request", "JSON Error in response");
}
catch(FacebookError e)
{
Log.d("Facebook-Example-Friends Request", "Facebook Error in response");
}
}
}
}
i think you see this answer you got some idea..
Facebook/Twitter Integration in my android application
and
http://android-sample-solution.blogspot.com

Categories

Resources