How do I get a Facebook profile picture?

Asked

Viewed 2,000 times

5

I’m having trouble downloading the profile photo. When I add this line, I start the id:

userIds2 = profile.getId();

Class

public class MainFragment extends android.support.v4.app.Fragment {

private Database databaseHelper;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private TextView mTextDetails;
private ImageView imageTeste;
private CallbackManager mCallbackManager;
private ImageView fbUserAvatar;
static String name;
static String idade;
private String userIds;
public String userIds2;
static byte[] image;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {

    @Override
    public void onSuccess(LoginResult loginResult) {
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        displayWelcomeMessage(profile);
        downloadAvatar();
        Intent it2 = new Intent(MainFragment.this.getActivity(), MainActivity.class);
        startActivity(it2);

    }
    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException e) {

    }
};
public MainFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    AccessTokenTracker tracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken old, AccessToken newToken) {

        }
    };

    ProfileTracker profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
            //displayWelcomeMessage(newProfile);
        }
    };
    tracker.startTracking();
    profileTracker.startTracking();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    loginButton.setFragment(this);
    loginButton.registerCallback(mCallbackManager, mCallback);
    imageTeste = (ImageView) view.findViewById(R.id.imageTeste);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
}

public void displayWelcomeMessage(Profile profile){
    if (profile != null){

        name = profile.getName();
        idade = profile.getLastName();
    }
}

private synchronized void downloadAvatar() {
    Profile profile = Profile.getCurrentProfile();
    userIds2 = profile.getId();
    AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
        @Override
        public Bitmap doInBackground(Void... params) {
            URL fbAvatarUrl = null;
            try {
                fbAvatarUrl = new URL("https://graph.facebook.com/"+userIds2+"/picture?type=large");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Bitmap fbAvatarBitmap = null;
            try {
                fbAvatarBitmap = BitmapFactory.decodeStream(fbAvatarUrl.openConnection().getInputStream());

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

            return fbAvatarBitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {//result vindo null, ver paginas que acessei ontem
            //imageTeste.setImageBitmap(result);

            image = convertBitmapToByteArray(result);

            databaseHelper = new Database(getActivity());

            boolean exist = databaseHelper.checkDataBase();
            if(exist == false) {

                Profile profile = Profile.getCurrentProfile();
                name = profile.getName();
                idade = profile.getLastName();
            long id2 = databaseHelper.insertData(name, idade, image);
            if(id2 < 0){
                Message.message(getActivity(), "Unsuccessful");
            } else{
                Message.message(getActivity(), "Successfully Inserted a Row");
            }
            }
        }

    };
    task.execute();
}

@Override
public void onResume() {
    super.onResume();
    Profile profile = Profile.getCurrentProfile();
    displayWelcomeMessage(profile);
}

@Override
public void onStop() {
    super.onStop();
    //mTokenTracker.stopTracking();
    //mProfileTracker.stopTracking();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

public static byte[] convertBitmapToByteArray(Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    } else {
        byte[] b = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
            b = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }
}

Error in the logcat

10-02 18:49:05.509    8338-8338/br.com.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: br.com.xxx, PID: 8338
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=129742, result=-1, data=Intent { (has extras) }} to activity {br.com.xxx/br.com.xxx.IntroActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3365)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
        at android.app.ActivityThread.access$1300(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at br.com.xxx.MainFragment.downloadAvatar(MainFragment.java:140)
        at br.com.xxx.MainFragment.access$000(MainFragment.java:46)
        at br.com.xxx.MainFragment$1.onSuccess(MainFragment.java:67)
        at br.com.xxx.MainFragment$1.onSuccess(MainFragment.java:60)
        at com.facebook.login.LoginManager.finishLogin(LoginManager.java:509)
        at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:192)
        at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:140)
        at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
        at br.com.xxx.MainFragment.onActivityResult(MainFragment.java:210)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:165)
        at android.app.Activity.dispatchActivityResult(Activity.java:5423)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)

            

3 answers

2

When I use the Facebook API I use a method I created to capture information like id, name, email, user photo. (I use the Loginmanager and Graphrequest everything from the Facebook documentation) And to help control the image I use the lib .Glide

Follows the code:


/**
 * Metodo para obter dados do facebook, id,nome,email,foto
 */
private void obterDadosFacebook(){

List permissionNeeds= Arrays.asList("email","user_about_me");

LoginManager.getInstance().logInWithReadPermissions(
        this,
        permissionNeeds);
LoginManager.getInstance().registerCallback(mCallbackManager,
        new FacebookCallback() {
            @Override
            public void onSuccess(LoginResult loginResults) {

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResults.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(
                                    JSONObject object,
                                    GraphResponse response) {
                                Log.v("TAG", "JSON: " + object);
                                try {
                                   //String foto = object.getJSONObject("picture").getJSONObject("data").getString("url");
                                   String id = object.getString("id");
                                   String foto = "https://graph.facebook.com/"+id+"/picture?height=120&width=120";
                                   String nome = object.getString("name");
                                   String email = object.getString("email");
                                    Glide.with(Context de sua class)
                                            .load(foto)
                                            .centerCrop()
                                            .error(R.drawable.erro)
                                            .into(profileImageView); // id do teu imageView.
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,picture.width(120).height(120)");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Log.e("TAG", "facebook login canceled");
            }

            @Override
            public void onError(FacebookException e) {
                Log.e("TAG", "facebook login failed error");
            }
        });
}

1

You can recover the URL of the user’s photo through your id:

private String recuperaFotoPerfilFacebook(String userID) throws MalformedURLException {
    Uri.Builder builder = Uri.parse("https://graph.facebook.com").buildUpon();
    builder.appendPath(userID).appendPath("picture").appendQueryParameter("type", "large");
    return builder.toString();
}

Now, with the image URL, you can load it normally.

0

I don’t know if it helps your Part but the most basic way to get the profile picture is like this:

Large https://graph.facebook.com/{facebookId}/picture?type=large

Medium https://graph.facebook.com/{facebookId}/picture?type=normal

Small https://graph.facebook.com/{facebookId}/picture?type=small

Square https://graph.facebook.com/{facebookId}/picture?type=square

Example: http://graph.facebook.com/1675697252718027/picture?type=large

Browser other questions tagged

You are not signed in. Login or sign up in order to post.