Eggsy
Eggsy

Reputation: 133

How to fetch username from facebook for android studio

I have been trying to fetch username from facebook by learning from this stackoverflow link

I am a new developer ,I really couldn't find a solution please check the code I have been working on,I new beginner please help

Please do not give me links I have tried everthing already, I request you to edit the code to help

public class MainActivity extends AppCompatActivity {

private TextView mTextDetails;
private CallbackManager mCallbackManager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    mCallbackManager=CallbackManager.Factory.create();
    setContentView(R.layout.activity_main);

    //instantiate callbacks manager
    mCallbackManager = CallbackManager.Factory.create();

}

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

    @Override
    public void onSuccess(LoginResult loginResult) {

        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        if (profile != null){
            mTextDetails = (TextView)findViewById(R.id.text_details);
            mTextDetails.setText("Welcome "+ profile.getName());
        }
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onError(FacebookException error) {

    }
};

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

Below is my XML file

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Welcome"
    android:id="@+id/text_details"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_above="@+id/login_button"/>

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp"
    android:layout_centerInParent="true"/>

I want the user name to be displayed in Textview in in the place of android:id="@+id/text_details"

Upvotes: 0

Views: 2642

Answers (1)

Natarajan Raman
Natarajan Raman

Reputation: 606

You can check this particular method called - UserinfoChangedCallback

https://developers.facebook.com/docs/reference/android/3.23.1/interface/LoginButton.UserInfoChangedCallback/

loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
            loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
                @Override
                public void onUserInfoFetched(GraphUser user) {
                    if (user != null) {
                        userName.setText("Hello, " + user.getName());
                    } else {
                        userName.setText("You are not logged");
                    }
                }
            });

userName is the TextView that I have in my app. On successful login, user name is displayed.

The complete code is,

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;

import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
import com.natarajan.drapjabdulkalam.R;

public class ShareHelper extends Activity{

        private LoginButton loginBtn;
        //private Button postImageBtn;
        private Button updateStatusBtn;

        private TextView fbquote;

        private TextView userName;

        private UiLifecycleHelper uiHelper;

        private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

        private String message;


        //private static String message = "Sample status posted from android app";

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

         // Add code to print out the key hash
            try {
                PackageInfo info = getPackageManager().getPackageInfo(
                        "com.facebook.samples.hellofacebook", 
                        PackageManager.GET_SIGNATURES);
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                    }
            } catch (NameNotFoundException e) {

            } catch (NoSuchAlgorithmException e) {

            }


            Intent intent = getIntent();

            message = intent.getStringExtra("quote");     


            uiHelper = new UiLifecycleHelper(this, statusCallback);
            uiHelper.onCreate(savedInstanceState);

            setContentView(R.layout.sharehelper_activity);

            fbquote = (TextView)findViewById(R.id.FbTextView);
            fbquote.setText(message);

            userName = (TextView) findViewById(R.id.user_name);
            loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
            loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
                @Override
                public void onUserInfoFetched(GraphUser user) {
                    if (user != null) {
                        userName.setText("Hello, " + user.getName());
                    } else {
                        userName.setText("You are not logged");
                    }
                }
            });

           /* postImageBtn = (Button) findViewById(R.id.post_image);
            postImageBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    postImage();
                }
            });*/

            updateStatusBtn = (Button) findViewById(R.id.update_status);
            updateStatusBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    postStatusMessage();
                }
            });

            buttonsEnabled(false);
        }

        private Session.StatusCallback statusCallback = new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                if (state.isOpened()) {
                    buttonsEnabled(true);
                    Log.d("FacebookSampleActivity", "Facebook session opened");
                } else if (state.isClosed()) {
                    buttonsEnabled(false);
                    Log.d("FacebookSampleActivity", "Facebook session closed");
                }
            }
        };

        public void buttonsEnabled(boolean isEnabled) {
          //  postImageBtn.setEnabled(isEnabled);
            updateStatusBtn.setEnabled(isEnabled);
        }

       /* public void postImage() {
            if (checkPermissions()) {
                Bitmap img = BitmapFactory.decodeResource(getResources(),
                        R.drawable.ic_launcher);
                Request uploadRequest = Request.newUploadPhotoRequest(
                        Session.getActiveSession(), img, new Request.Callback() {
                            @Override
                            public void onCompleted(Response response) {
                                Toast.makeText(ShareHelper.this,
                                        "Photo uploaded successfully",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                uploadRequest.executeAsync();
            } else {
                requestPermissions();
            }
        } */

        public void postStatusMessage() {
            if (checkPermissions()) {
                Request request = Request.newStatusUpdateRequest(
                        Session.getActiveSession(), message,
                        new Request.Callback() {
                            @Override
                            public void onCompleted(Response response) {
                                if (response.getError() == null)
                                    Toast.makeText(ShareHelper.this,
                                            "Quote Shared successfully",
                                            Toast.LENGTH_LONG).show();
                            }
                        });
                request.executeAsync();
            } else {
                requestPermissions();
            }
        }

        public boolean checkPermissions() {
            Session s = Session.getActiveSession();
            if (s != null) {
                return s.getPermissions().contains("publish_actions");
            } else
                return false;
        }

        public void requestPermissions() {
            Session s = Session.getActiveSession();
            if (s != null)
                s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSIONS));
        }

        @Override
        public void onResume() {
            super.onResume();
            uiHelper.onResume();
            buttonsEnabled(Session.getActiveSession().isOpened());
        }

        @Override
        public void onPause() {
            super.onPause();
            uiHelper.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            uiHelper.onDestroy();
        }

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

        @Override
        public void onSaveInstanceState(Bundle savedState) {
            super.onSaveInstanceState(savedState);
            uiHelper.onSaveInstanceState(savedState);
        }
}

and the XML is,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_facebook"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:background="@drawable/bg1"
    android:orientation="vertical"
    android:padding="20dp" >

    <com.facebook.widget.LoginButton
        android:id="@+id/fb_login_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        facebook:confirm_logout="false"
        android:background="@color/com_facebook_blue"
        android:textStyle="bold"
        facebook:fetch_user_info="true" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:textSize="18sp" />

    <Button
        android:id="@+id/update_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:textStyle="bold"
        android:textColor="@color/com_facebook_loginview_text_color"
        android:background="@color/com_facebook_blue"
        android:text="@string/update_status" />

    <TextView
        android:id="@+id/FbTextView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:background="#FFFFFF"
        android:text="@string/welcometext"
        android:textSize="20sp"
        android:gravity="left|center"
        android:textColor="#0B0A0A"
        android:padding="10dp"
        android:textStyle="bold" 
        /> 


 <!--    <Button
        android:id="@+id/post_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/post_image" />  -->

</LinearLayout>

Upvotes: 3

Related Questions