Research Development
Research Development

Reputation: 904

how to fetch image and display in image view from facebook

loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                if (user != null) {
                    userName.setText("Hello, " + user.getName());

                    Bitmap bitmap1 = getFacebookProfilePicture(user.getId());

                    imgview.setImageBitmap(bitmap1);
                } else {
                    userName.setText("You are not logged");
                }
            }
        });
public Bitmap getFacebookProfilePicture(String userID) {

        try {
            URL imageURL = new URL("https://graph.facebook.com/" + userID
                    + "/picture?type=large");
            bitmap = BitmapFactory.decodeStream(imageURL.openConnection()
                    .getInputStream());

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;

    }

This is my code i am trying to get Profile pic from Facebook and display it on image-view in my app i am able to get name from Facebook but when i put code for get Profile pic then i am unable to get image in android please tell me where am doing wrong give me solution how to set this code .

Upvotes: 1

Views: 2955

Answers (3)

Sheychan
Sheychan

Reputation: 2436

Assuming you got the right access tokens, The updated API shows picture field in JSON like this:

{
"id": "8169595750129122",
"name": "A user name",
"picture": {
    "data": {
        "is_silhouette": false,
        "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xtp1/v/t1.0-1/p50x50/11150668_881451758563505_2749775492727269008_n.jpg?oh=35239d96bf3a6d34bd455c51218412d9&oe=56487861&__gda__=1446869670_cd2511b71fc9b8809d6b52bdbb451ff0"
    }
  }
}

If you want to get the picture url for example after logging in

LoginButton login_button = (LoginButton) view.findViewById(R.id.login_button);


    callbackManager = CallbackManager.Factory.create();
    login_button.setFragment(this);
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    GraphRequest request = GraphRequest.newMeRequest(
                            AccessToken.getCurrentAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {
                                    try {



 //THIS CONTAINS the URL String displaying it is up to you
String PROFPIC_URL = object.getJSONObject("picture").getJSONObject("data").getString("url");
String FIRSTNAME = object.getString("first_name");


                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,picture,last_name,first_name");
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                @Override
                public void onCancel() {
                    textview.setText("Facebook Login Cancelled");
                }

                @Override
                public void onError(FacebookException exception) {
                    textview.setText("Facebook Login Error");
                }
            });

You can do values experiments in here https://developers.facebook.com/tools/explorer/

Upvotes: 0

Alex Kombo
Alex Kombo

Reputation: 3356

Use callbacks, they are much easier. Create a callback as follows;

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {

    @Override
    public void onSuccess(LoginResult loginResult) {

        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                if(jsonObject != null){
                    try {
                        String name = jsonObject.getString("name");
                        String email = jsonObject.getString("email");
                        String id = jsonObject.getString("id");

                        saveCurrentProfileInfo(id, name, email);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id, email, name");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
        createSnackBar("Facebook login cancelled");
    }

    @Override
    public void onError(FacebookException e) {
        createSnackBar("Error logging in to Facebook");
    }
};

Then on your oncreate method, initialize a CallbackManager

CallbackManager callbackManager = CallbackManager.Factory.create();

loginButton.registerCallback(callbackManager, callback);

You can then use the id retrieved to get the profile picture like you did.

Upvotes: 0

Rajesh Jadav
Rajesh Jadav

Reputation: 12861

Use this method to get Bitmap from Url.

 /**
     * Download image from server url and return bitmap
     *
     * @param stringUrl Imaage download url
     * @return Bitmap receieved from server
     */
    private Bitmap downloadImage(String stringUrl) {
        URL url;
        Bitmap bm = null;
        try {
            url = new URL(stringUrl);
            URLConnection ucon = url.openConnection();
            InputStream is;
            if (ucon instanceof HttpURLConnection) {
                HttpURLConnection httpConn = (HttpURLConnection) ucon;
                int statusCode = httpConn.getResponseCode();
                if (statusCode == 200) {
                    is = httpConn.getInputStream();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 8;
                    BufferedInputStream bis = new BufferedInputStream(is, 8192);
                    ByteArrayBuffer baf = new ByteArrayBuffer(1024);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                    }
                    byte[] rawImage = baf.toByteArray();
                    bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
                    bis.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

Pass Facebook Profile pic url to this method like this and set downloaded bitmap to imageview.

 URL imageURL = new URL("https://graph.facebook.com/" + userID
                    + "/picture?type=large");

 imgview.setImageBitmap(downloadImage(imageURL));

I hope it helps!

Upvotes: 1

Related Questions