I don\'t know why, but I am always getting null when I try to get the profile picture of the user. Do I need to set some specific permissions to get access?
Below is
Facebook API Graph Version 3.2
I've made this implementation:
First make shure you have this permissions added in "onStart" or "onCreate" (This avoids the NetworkOnMainThreadException).
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
After that you can use the next function:
//Next lines are Strings used as params
public static String FACEBOOK_FIELD_PROFILE_IMAGE = "picture.type(large)";
public static String FACEBOOK_FIELDS = "fields";
//A function that can be accessed from OnCreate (Or a similar function)
private void setImageProfileFacebook(){
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if(isLoggedIn) {
//If the user is LoggedIn then continue
Bundle parameters = new Bundle();
parameters.putString(Util.FACEBOOK_FIELDS, Util.FACEBOOK_FIELD_PROFILE_IMAGE);
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me",
parameters,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
if (response != null) {
try {
JSONObject data = response.getJSONObject();
//Log.w(TAG, "Data: " + response.toString());
if (data.has("picture")) {
boolean is_silhouette = data.getJSONObject("picture").getJSONObject("data").getBoolean("is_silhouette");
if (!is_silhouette) {
//Silhouette is used when the FB user has no upload any profile image
URL profilePicUrl = new URL(data.getJSONObject("picture").getJSONObject("data").getString("url"));
InputStream in = (InputStream) profilePicUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
imageViewProfileFisio.setImageBitmap(bitmap);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.w(TAG, "Response null");
}
}
}
).executeAsync();
}
}
My example was created using the official documentation: https://developers.facebook.com/docs/graph-api/reference/profile-picture-source/?locale=es_LA
You are getting null because the call to URL.openConnection() (or any other mechanism to fetch the image) is asynchronous. It returns after your line: return bitmap;
. Therefore bitmap is always null.
I suggest using a callback instead.
This is what i did:
final AQuery androidQuery = new AQuery(this);
AjaxCallback<byte[]> imageCallback = new AjaxCallback<byte[]>() {
@Override
public void callback(String url, byte[] avatar, AjaxStatus status) {
if (avatar != null) {
save(avatar);
} else {
Log.e(TAG, "Cannot fetch third party image. AjaxStatus: " + status.getError());
}
}
};
androidQuery.ajax(imageUrl, byte[].class, imageCallback);
Android query allows you to get the image in different formats (e.g. byte array, Bitmap, etc.). There are other libraries out there, but the idea is the same.
I search all modes to make this on API 15 only this method work for me whith Volley:
String url = "https://graph.facebook.com/"+ fid +"/picture?type=square";
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(request);
NOTE: From 26 Mar 2018, all solutions related to manual link don't work anymore
You should follow the official guide here
private static String FACEBOOK_FIELD_PROFILE_IMAGE = "picture.type(large)";
private static String FACEBOOK_FIELDS = "fields";
private void getFacebookData() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
(object, response) -> {
updateAvatar(getImageUrl(response));
});
Bundle parameters = new Bundle();
parameters.putString(FACEBOOK_FIELDS, FACEBOOK_FIELD_PROFILE_IMAGE);
request.setParameters(parameters);
request.executeAsync();
}
private static String FACEBOOK_FIELD_PICTURE = "picture";
private static String FACEBOOK_FIELD_DATA = "data";
private static String FACEBOOK_FIELD_URL = "url";
private String getImageUrl(GraphResponse response) {
String url = null;
try {
url = response.getJSONObject()
.getJSONObject(FACEBOOK_FIELD_PICTURE)
.getJSONObject(FACEBOOK_FIELD_DATA)
.getString(FACEBOOK_FIELD_URL);
} catch (Exception e) {
e.printStackTrace();
}
return url;
}
This should work:
public static Bitmap getFacebookProfilePicture(String userID){
URL imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
Bitmap bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
return bitmap;
}
Bitmap bitmap = getFacebookProfilePicture(userId);
As suggested by @dvpublic in the comments, the problem of image not being downloaded is fixed using by "https" in favour of "http".
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
String imageURL = "https://graph.facebook.com/" + mFbUserId +"/picture?width=150&width=150";
URL imageURI = new URL(imageURL);
bitmap = BitmapFactory.decodeStream(imageURI.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}.execute();