简体   繁体   English

在导航抽屉活动中显示获取的个人资料图片

[英]Displaying fetched profile picture in Navigation drawer activity

Hope you can notice a prof pic in this below Image 希望您可以在下面的这张图片中注意到教授图片 在此处输入图片说明 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. 我已经从Facebook提取了用户名,电子邮件ID和prof图片,并且已经将用户名和E-mail ID与导航抽屉活动挂钩,但是我不知道如何显示从Facebook提取的prof_pic我只是不知道没有如何分配它。 let me know if there is any possible way to do it.the below is the nav_header.xml 让我知道是否有任何可能的方法。以下是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 这是我需要从.java类文件中获取prof_pic的Java文件

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 这是我用来获取用户名,邮件ID和教授图片的.java文件

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

}

The best way would be using Picasso Library. 最好的方法是使用Picasso Library。 It automatically fetches image from url in background and sets it to the imageView. 它会自动从后台url获取图像并将其设置为imageView。

Add this to the build.gradle file under dependencies 将此添加到依赖项下的build.gradle文件中

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

And then in your code instead of profilePictureView.setProfileId(); 然后在您的代码中而不是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. 其中userID是配置文件的已使用ID。

I don't know what this does: 我不知道这是做什么的:

profilePictureView.setProfileId();

But to set the image just use: 但是要设置图像,只需使用:

profilePictureView.setImageBitmap(pass_image_bitmap_here);

You can always you image loading library for loading images in efficient way (Like Picasso or Glide ). 您始终可以使用图像加载库来高效地加载图像(例如PicassoGlide )。 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 如果您的网址= https://graph.facebook.com/ “ + id +” / picture?width = 200&height = 150

I hope this helps. 我希望这有帮助。

All you need is the user ID for the user, then you can call a function like this: 您需要的只是用户的用户ID,然后可以调用以下函数:

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

This is the way that I came up with. 这就是我想出的方式。

Use Picasso library which is used for image processing in android. 使用Picasso库,该库用于android中的图像处理。

  1. Add dependency in gradle: 在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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM