5

Eu estou tendo problemas para fazer o download da foto do perfil. Quando eu adiciono essa linha, inicializando o id:

userIds2 = profile.getId();

Classe

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;
    }
}

Erro no 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)

            

0

3 Respostas 3

2

Quando eu uso a API do Facebook eu utilizo um método que eu criei para capturar informações como id,nome,email,foto do usuário. (Eu uso o LoginManager e GraphRequest tudo da documentação do Facebook) E para ajudar no controle da imagem eu utilizo a lib .glide

Segue o código:


/**
 * 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

Você pode recuperar a URL da foto do usuário através do seu 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();
}

Agora, com a URL da imagem, você pode carrega-la normalmente.

0

Nao sei se ajuda para o seu casso mas a forma mais básica de obter a foto de perfil e assim:

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

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

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .