I am trying to learn Facebook API for android. I tried to login and it's logging it. But I am not able to get any information from the user profile. It is not returning anything in the textview that is intended to show the name of the Facebook user logged in.
public class ProfileScreenFragment extends Fragment {
private TextView mTextView;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private CallbackManager mCallbackManager;
private FacebookCallback<LoginResult> mCallback=new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken=loginResult.getAccessToken();
Profile profile=Profile.getCurrentProfile();
displayWelcomeMessage(profile);
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
}
};
public ProfileScreenFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager=CallbackManager.Factory.create();
mTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
}
};
mProfileTracker=new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
}
};
mTokenTracker.startTracking();
mProfileTracker.startTracking();
}
public void displayWelcomeMessage(Profile profile){
if(profile!=null){
mTextView.setText("Welcome "+profile.getName());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_screen, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton=(LoginButton)view.findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile");
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager,mCallback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode,resultCode,data);
}
@Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayWelcomeMessage(profile);
}
@Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
}
This is what I get in logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getName()' on a null object reference
How do I obtain the profile name using the textview inside the displayWelcomeMessage() function ? Thanks.