Displaying fetched profile picture in Navigation d

2019-06-02 22:34发布

Hope you can notice a prof pic in this below Imageenter image description here but the random guy who did it just hard coded the Image. I have fetched the username, E-mail ID and prof pic from Facebook and I have hooked username and E-mail id with navigation drawer activity,but I don't know how to display the prof_pic which I fetched from Facebook I just don't no how to assign it. let me know if there is any possible way to do it.the below is the nav_header.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <ImageView
        android:id="@+id/profpic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

</LinearLayout>

and this is the java file where I need to fetch the prof_pic from .java class file

public class Testing2 extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testing2);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ////////Code is used to fetch the user name////////////
        Bundle b = getIntent().getExtras();


        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        TextView facebookName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.manner);
        TextView Email = (TextView) navigationView.getHeaderView(0).findViewById(R.id.email);
        ImageView profilePictureView = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.profpic);

        ////////Code is used to display the user name after fetching it from other activity////////////
        facebookName.setText(b.getCharSequence("name"));
        Email.setText(b.getCharSequence("email"));
        profilePictureView.setProfileId();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

  } 

This is the .java file where I used to fetch the username,mail Id and prof pic

public class SelfTrail extends AppCompatActivity implements View.OnClickListener {

    private LoginButton btnLogin;
    TextView facebookName;
    TextView Email;
    Button button;
    private CallbackManager callbackManager;
    private ProfilePictureView profilePictureView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_self_trail);
        findAllViewsId();
        button.setOnClickListener(this);

        btnLogin = (LoginButton)findViewById(R.id.login_button);
        facebookName = (TextView)findViewById(R.id.name);
        Email = (TextView)findViewById(R.id.Email);
        profilePictureView = (ProfilePictureView)findViewById(R.id.image);


        btnLogin.setReadPermissions(Arrays.asList("public_profile, email"));
        callbackManager = CallbackManager.Factory.create();

        if(AccessToken.getCurrentAccessToken() != null){
            RequestData();
            facebookName.setVisibility(View.VISIBLE);
            Email.setVisibility(View.VISIBLE);
            profilePictureView.setVisibility(View.VISIBLE);
        }

        btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email");
                request.setParameters(parameters);
                request.executeAsync();

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException exception) {

            }
        });
       }




    private void findAllViewsId() {
        button = (Button) findViewById(R.id.next);
        facebookName = (TextView)findViewById(R.id.name);
        Email = (TextView)findViewById(R.id.Email);
        profilePictureView = (ProfilePictureView)findViewById(R.id.image);
    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent(getApplicationContext(), Testing2.class);
        //Create a bundle object
        Bundle b = new Bundle();

        //Inserts a String value into the mapping of this Bundle
        b.putString("name", facebookName.getText().toString());
        b.putString("email", Email.getText().toString());
        b.putString("image", profilePictureView.toString());

        //Add the bundle to the intent.
        intent.putExtras(b);

        //start the DisplayActivity
        startActivity(intent);
    }

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


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

                JSONObject json = response.getJSONObject();
                try {
                    if(json != null){
                        facebookName.setText(jsonObject.getString("name"));
                        Email.setText(jsonObject.getString("email"));
                        profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
                        profilePictureView.setProfileId(jsonObject.getString("id"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }


    private void setProfileToView(JSONObject jsonObject) {
        try {
            facebookName.setText(jsonObject.getString("name"));
            Email.setText(jsonObject.getString("email"));

            profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
            profilePictureView.setProfileId(jsonObject.getString("id"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

5条回答
小情绪 Triste *
2楼-- · 2019-06-02 22:41

The best way would be using Picasso Library. It automatically fetches image from url in background and sets it to the imageView.

Add this to the build.gradle file under dependencies

          compile 'com.squareup.picasso:picasso:2.5.2'

And then in your code instead of profilePictureView.setProfileId(); use

          Picasso.with(this).load( "http://graph.facebook.com/"+userID+"/picture?type=small").into(profilePictureView)

Where userID is the used id of the profile.

查看更多
smile是对你的礼貌
3楼-- · 2019-06-02 22:51

All you need is the user ID for the user, then you can call a function like this:

/**
 * Function loads the users facebook profile pic
 * 
 * @param userID
 */
public Bitmap getUserPic(String userID) {
    String imageURL;
    Bitmap bitmap = null;
    Log.d(TAG, "Loading Picture");
    imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
    try {
        bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
    } catch (Exception e) {
        Log.d("TAG", "Loading Picture FAILED");
        e.printStackTrace();
    }
    return bitmap;
}
查看更多
forever°为你锁心
4楼-- · 2019-06-02 22:53

You can always you image loading library for loading images in efficient way (Like Picasso or Glide). In you case, (using Picasso) you can write

Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.loading_img)
       .error(R.drawable.error_img)
       .into(profilePictureView);

Where your url = https://graph.facebook.com/" + id + "/picture?width=200&height=150

I hope this helps.

查看更多
beautiful°
5楼-- · 2019-06-02 23:02

I don't know what this does:

profilePictureView.setProfileId();

But to set the image just use:

profilePictureView.setImageBitmap(pass_image_bitmap_here);

查看更多
我想做一个坏孩纸
6楼-- · 2019-06-02 23:03

This is the way that I came up with.

Use Picasso library which is used for image processing in android.

  1. Add dependency in gradle:

    compile 'com.squareup.picasso:picasso:2.5.2'

  2. Add in your activity to display the fetched image:

    Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.loading_img)
       .error(R.drawable.error_img)
       .into(profilePictureView);
    
查看更多
登录 后发表回答